FactoryGirl and Rspec Testing Association Membership

I have the following model:

class Team < ActiveRecord::Base # Setup accessible (or protected) attributes for your model attr_accessible :name validates_presence_of :name belongs_to :user end 

What is being tested:

 describe Team do before(:each) do @attr = FactoryGirl.attributes_for(:team) end it "should belong to a user" do @team = Team.create!(@attr) @team.should belong_to(:user) end end 

And I have the following factories:

 FactoryGirl.define do factory :team do name 'Dream Team' sport user end end FactoryGirl.define do factory :user do name 'Test User' last_name 'Last Name' email ' example@example.com ' password 'changeme' password_confirmation 'changeme' end end 

When I test the specification, I get the following failure:

1) The team must belong to the user Error / Error: @team = Team.create! (@Attr) ActiveRecord :: StatementInvalid: SQLite3 :: ConstraintException: teams.user_id cannot be NULL: INSERT INTO "teams" ("created_at", "name", "sport_id", "updated_at", "user_id") VALUES ( ?,?,?,?,?)

Why? The docs say that to set up an association, you can just write the name Factory, in my case this is a user.

thanks

+4
source share
2 answers

FactoryGirl.attributes_for will provide you with a hash containing attributes only for the specified model, not including association attributes - in your case user_id .

This will cause errors if user_id is a required field and you are trying to create an instance of Team using FactoryGirl.create(attributes_for(:team)) .

However, if you use FactoryGirl.create(:team) , it should provide you with a valid instance of Team .

+4
source

You should not use before(:each) with FactoryGirl and Rspec, in fact the more elegant way to create this test, according to The Rails 4 Way Chapter 21, is to use let(:team) { FactoryGirl.create(:team } before your statements

this allows you not to use so many instance variables, if desired, I can give an example if this explanation is not enough.

0
source

All Articles