Reputation: 6346
I have the following factories defined in my factories.rb file:
require 'factory_girl'
FactoryGirl.define do
sequence(:email) {|n| "person-#{n}@example.com" }
factory :country do
...
end
factory :state do
country
...
end
factory :school do
name "Test School"
country
state
end
factory :user do
school
email
...
end
end
When testing in rspec calling FactoryGirl.create(:school)
in one of my descriptors causes two schools with the name "Test School" to be created.
I thought the factories defined in factories.rb were just a bunch of unsaved instance objects, can somebody clarify as to why I'm having this issue?
Here's the exact rspec:
require 'spec_helper'
describe "school login" do
it "displays a success message upon successful login to school",do
school = FactoryGirl.create(:school)
user = FactoryGirl.create(:user, :username => "jdoe")
School.all.each do |school|
puts school.name #2x => "Test School"
end
visit school_path(user.school)
click_link('login')
fill_in "username", :with => "jdoe"
fill_in "password", :with => "secret"
click_button "Sign in"
expect(page).to have_selector(".alert-success")
end
end
Upvotes: 2
Views: 775
Reputation: 2365
This line creates the first school
school = FactoryGirl.create(:school)
and this one the second:
user = FactoryGirl.create(:user, :username => "jdoe")
This happens because in your user factory you defined that every user should have a school, so FactoryGirl is creating it for you. If you want your user associated with the first school, you can do something like this:
user = FactoryGirl.create(:user, :username => "jdoe", :school => school)
Upvotes: 2
Reputation: 21549
what's the context code? and how did you find there are 2 schools
created?
the code written in ruby files ( factories ) is neither saved to database nor created as object until you declare create(:object)
or build(:object)
.
# Returns a User instance that's not saved
user = FactoryGirl.build(:user)
# Returns a saved User instance
user = FactoryGirl.create(:user)
for more details, refer to : https://github.com/thoughtbot/factory_girl/blob/master/GETTING_STARTED.md#using-factories
Upvotes: 0