[rspec-devel] [ rspec-Bugs-6905 ] Mocking rails associations where the association is validated

noreply at rubyforge.org noreply at rubyforge.org
Sun Nov 26 22:41:45 EST 2006


Bugs item #6905, was opened at 2006-11-26 20:41
You can respond by visiting: 
http://rubyforge.org/tracker/?func=detail&atid=3149&aid=6905&group_id=797

Category: None
Group: None
Status: Open
Resolution: None
Priority: 3
Submitted By: Pat Maddox (pergesu)
Assigned to: Nobody (None)
Summary: Mocking rails associations where the association is validated

Initial Comment:
Take the following model

class Person < ActiveRecord::Base
  belongs_to :user
  validates_presence_of :name, :user
end

the following spec

  specify "should create a new person" do
    @u.should_receive(:to_param).and_return("pat")
    @u.should_receive(:people).and_return([])
    @before_count = Person.count
    post :create, :user_id => "pat", :person => { :name => "BJ" }
    Person.should_have(@before_count + 1).records
  end

and the following action

  def create
    @user = User.find_by_login params[:user_id]
    @person = Person.new params[:person]
    @user.people << @person
    redirect_to person_path(@user, @person)
  end

The spec fails because the Person can't be saved.  The Person can't be saved because it fails the validates_presence_of :user.  In Rails, the collection is a proxy rather than simply an array, and the << method is written such that it would actually set @person.user in the above code.  A simple array of course doesn't do that.

I've got an idea to handle this, which involves writing a basic class that does all the setting, and returning that for people instead of an array.  That ought to work.

The code behaves as expected, but the spec does not.

The other way you would do this association is to do
@person.user = @user

but Rails does some type checking here, and you get
User expected, got Spec::Mocks::Mock

No problem, just do
@user.should_receive(:class).and_return(User)
BUT you get
User expected, got User

hrm.  I made it return the string "User" instead of the class and got the same thing.

I'm going to work on a rails-like collection class, since that's what I'm most interested in at the moment.  Not sure what to do about the strange "User expected, got User" when assigning the value of a belongs_to.

----------------------------------------------------------------------

You can respond by visiting: 
http://rubyforge.org/tracker/?func=detail&atid=3149&aid=6905&group_id=797


More information about the rspec-devel mailing list