FactoryGirl和Rspec测试中attributes_for的含义

jas*_*328 33 attributes rspec ruby-on-rails ruby-on-rails-3 factory-bot

通过关于控制器测试的教程,作者给出了测试控制器动作的rspec测试的示例.我的问题是,为什么他们使用的方法attributes_forbuildattributes_for除了它返回值的散列之外,没有明确的解释.

it "redirects to the home page upon save" do
  post :create, contact: Factory.attributes_for(:contact)
  response.should redirect_to root_url
end
Run Code Online (Sandbox Code Playgroud)

可在此处找到教程链接:http://everydayrails.com/2012/04/07/testing-series-rspec-controllers.html该示例位于开头主题部分Controller testing basics

pja*_*jam 62

attributes_for将返回一个哈希值,而build返回一个非持久化对象.

鉴于以下工厂:

FactoryGirl.define do
  factory :user do
    name 'John Doe'
  end
end
Run Code Online (Sandbox Code Playgroud)

结果如下build:

FactoryGirl.build :user
=> #<User id: nil, name: "John Doe", created_at: nil, updated_at: nil>
Run Code Online (Sandbox Code Playgroud)

和结果 attributes_for

FactoryGirl.attributes_for :user
=> {:name=>"John Doe"}
Run Code Online (Sandbox Code Playgroud)

我发现attributes_for我的功能测试非常有用,因为我可以执行以下操作来创建用户:

post :create, user: FactoryGirl.attributes_for(:user)
Run Code Online (Sandbox Code Playgroud)

使用时build,我们必须从user实例手动创建属性哈希并将其传递给post方法,例如:

u = FactoryGirl.build :user
post :create, user: u.attributes # This is actually different as it includes all the attributes, in that case updated_at & created_at
Run Code Online (Sandbox Code Playgroud)

当我直接想要对象而不是属性哈希时,我通常使用build&create

如果您需要更多详细信息,请告诉我们