定義工廠

如果你有一個帶有名稱和電子郵件屬性的 ActiveRecord User 類,你可以通過使 FactoryGirl 猜測它來為它建立一個工廠:

FactoryGirl.define do
  factory :user do # it will guess the User class
    name     "John"
    email    "john@example.com"
  end
end

或者你可以明確甚至更改其名稱:

FactoryGirl.define do
  factory :user_jack, class: User do
    name     "Jack"
    email    "jack@example.com"
  end
end

然後在你的規範中,你可以使用 FactoryGirl 的方法,如下所示:

# To create a non saved instance of the User class filled with John's data 
build(:user) 
# and to create a non saved instance of the User class filled with Jack's data
build(:user_jack)

最常見的方法是:

# Build returns a non saved instance
user = build(:user)

# Create returns a saved instance
user = create(:user)

# Attributes_for returns a hash of the attributes used to build an instance
attrs = attributes_for(:user)