Factorygirl Admin Creation

2019-08-05 10:02发布

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!

2条回答
在下西门庆
2楼-- · 2019-08-05 10:41

Yes, that is correct. When you create a nested FactoryGirl object, that object inherits all attributes of its parent.

查看更多
霸刀☆藐视天下
3楼-- · 2019-08-05 10:59

Assuming you already know how FactoryGirl library works, the explanation to your question is that the :admin factory is defined inside the :user factory

FactoryGirl.define do
  factory :user do
    ...

    factory :admin do
      admin true
    end
  end
end

In this case, :admin will inherit all the properties of the user, plus the specific admin: true setting.

FactoryGirl.create(:admin)
查看更多
登录 后发表回答