Reputation: 2422
I have the following spec:
it "saves a default 'active' status if not specified" do
if User.count <= 0
user = User.new(FactoryGirl.attributes_for(:user))
user.save
end
project = FactoryGirl.create(:project, :status => nil)
project.status.should eq("active")
end
With this FactoryGirl object:
factory :project do
title "A short title"
description "A short description"
parent_id 1
pm_id 1
status "active"
end
The project's model validates the presence of an association... so, before testing, I would like to save a user inside test database. But the code above doesn't save anything in the DB.
Instead, If I add a before(:all) block:
before(:all) do @user = User.new(FactoryGirl.attributes_for(:user)) @user.save end
a new user gets saved into the database. Why?
Upvotes: 3
Views: 1251
Reputation: 698
If, in your model, the Project belongs_to the User then you can have factory girl simply create a user as it creates a project. You would just update your Project factory to
factory :project do
title "A short title"
description "A short description"
parent_id 1
pm_id 1
status "active"
user
end
I think this would have the same effect as the code you have above.
Secondly in the code above you don't appear to be associating the project with the user at any point. (Assuming of course that neither pm_id or parent_id refer to the user, which case can I recommend that you don't make assumptions about the ids and use the method above instead :-)
Upvotes: 2