RSpec - Having trouble mocking model associations

Hi everyone,

I’m having a devil of a time trying to figure out why this spec keeps
giving
me an error. I’m attempting to mock out a class I haven’t created yet
(User) so I don’t need to worry about creating it at the moment. I
could
have sworn I read somewhere that it was possible to pass a mock object
as an
attribute to an associated class, but it’s just not working for me.

Here’s the code I have:

task_spec.rb

describe Task do
before(:each) do
user_proxy = mock(‘user’)
@task = Task.new(
:description => “Sample task description”,
:assigned_user => user_proxy
)
end

it “should be valid with all required attributes” do
@task.should be_valid
end

it “should be invalid without a description” do
@task.description = nil
@task.should_not be_valid
@task.should have(1).error_on(:description)
end

it “should be invalid unless assigned to a user” do
@task.assigned_user = nil
@task.should_not be_valid
@task.should have(1).error_on(:assigned_user_id)
end
end

task.rb

class Task < ActiveRecord::Base
belongs_to :assigned_user, :class => “User”, :foreign_key =>
“assigned_user_id”

validates_presence_of :description
validates_presence_of :assigned_user_id # Validate against the foreign
key, not the association
end


When I try to run this, I get an error stating “uninitialized constant
Task::User”, presumably because of the belongs_to – I’m certain I saw
somewhere that you could mock this so I didn’t have to create the User
class when I’m only concerned with the Task class, but I can’t for the
love
of me figure out how it was done, and I can’t remember where it was I
saw it
to check.

The problem I’m having is that the two validation checks are working,
but no
matter what the first one (the one that checks if it IS valid) always
returns false. I tried changing the before block to this:

before(:each) do
user_proxy = mock(‘user’, :id => 1)
@task = Task.new(
:description => “Sample”
)
@task.stub!(:assigned_user).and_return(user_proxy)
end

but still nothing; the “should be valid” spec fails, but the other two
are
passing like they should. I attempted to debug the code by checking
that
there were no error messages ( e.g. @task.errors.full_messages.should ==
[]
) and that passed, but valid? is still showing as false.

As you can probably tell, I’m a little new to using RSpec and BDD, and
I’ve
never done anything with mocks or stubs before. None of the tutorials
I’ve
read through so far have dealt with a model that has associations, and
needs
to make sure that it’s assigned to an association. In this case I’m
trying
to make sure that a task has been assigned to a user before it gets
saved,
but I’m trying to avoid having to stop and create the User class, since
I’m
not sure at this point how I’m going to implement it, and I don’t want
to
implement a dummy class.

If someone could point me in the right direction, I’d greatly appreciate
it.