Rspec Mocking: ActiveRecord :: AssociationTypeMismatch

I am new to Rspec and am trying to set up a test for a user profile. The profile belongs to _.

Now I have API integration with a third-party site that works through the user model, but some of the information for this API link is contained in the profile, so I have an after_update filter in the profile that tells the parent user who starts the API update.

I try to write a test for this, and I get ActiveRecord :: AssociationTypeMismatch. The reason is that I am using the user layout, but I am trying to verify that when the profile is updated, it sends: save to User. In addition, the user model has an email verification process, and the associated API calls create the process, so it’s actually not ideal to actually create a user to verify this.

Here is my test:

it "should save the parent user object after it is saved" do user = double('user', :save => true ) profile = Profile.create( :first_name => 'John', :last_name => 'Doe' ) profile.user = user user.should_receive(:save) end 

So, it’s obvious that the ActiveRecord error was caused by an attempt to associate a layout with a profile that expects the real user to be connected.

My question is: how to avoid such a problem when writing tests on rails? All I want to do is check that the profile calls: save the parent on it. Is there a smarter way to do this or a workaround for an ActiveRecord error?

Thanks!

+6
ruby-on-rails activerecord ruby-on-rails-3 mocking rspec
source share
2 answers

I found the only way I was able to get around this problem was to use the Factory user instead of the layout. This is disappointing, but when testing callbacks between two ActiveRecord models, you need to use real models, otherwise the call will fail, the life cycle will not happen, and the callbacks will not be verified.

+3
source share

You can use mock_model for this:

 it "should save the parent user object after it is saved" do user = mock_model(User) user.should_receive(:save).and_return(true) profile = Profile.create( :first_name => 'John', :last_name => 'Doe' ) profile.user = user end 
+11
source share

All Articles