RSpec - Having trouble mocking model associations

Hi everyone,

I’m having a devil of a time trying to figure out why this spec keeps
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
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:


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

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

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

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)


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

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

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
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 =
:description => “Sample”

but still nothing; the “should be valid” spec fails, but the other two
passing like they should. I attempted to debug the code by checking
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
never done anything with mocks or stubs before. None of the tutorials
read through so far have dealt with a model that has associations, and
to make sure that it’s assigned to an association. In this case I’m
to make sure that a task has been assigned to a user before it gets
but I’m trying to avoid having to stop and create the User class, since
not sure at this point how I’m going to implement it, and I don’t want
implement a dummy class.

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs