I am following Michael Hartl's online tutorial and in Listing 9.42, I am having trouble comprehending the code.
FactoryGirl.define do
factory :user do
sequence(:name) { |n| "Person #{n}" }
sequence(:email) { |n| "person_#{n}@example.com"}
password "foobar"
password_confirmation "foobar"
factory :admin do
admin true
end
end
end
Then admin is created in listing 9.43
describe "as an admin user" do
let(:admin) { FactoryGirl.create(:admin) }
What I don't understand is how that is possible to create an admin without any code of
sequence(:name) { |n| "Person #{n}" }
sequence(:email) { |n| "person_#{n}@example.com"}
password "foobar"
password_confirmation "foobar"
inside the admin block?
It seems :admin block is nested inside :user block and so the :user block code is executed during FactoryGirl.create(:admin)
creating an admin with users name, email, password inside the :user block?
Is that right? Thank you!
Yes, that is correct. When you create a nested FactoryGirl object, that object inherits all attributes of its parent.
Assuming you already know how FactoryGirl library works, the explanation to your question is that the
:admin
factory is defined inside the:user
factoryIn this case,
:admin
will inherit all the properties of the user, plus the specificadmin: true
setting.