定义工厂
如果你有一个带有名称和电子邮件属性的 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)