39

浏览有关控制器测试的教程,作者给出了一个 rspec 测试测试控制器动作的示例。attributes_for我的问题是,他们为什么要使用这种方法buildattributes_for除了返回值的散列之外,没有明确的解释为什么使用它。

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

教程链接在这里:http ://everydayrails.com/2012/04/07/testing-series-rspec-controllers.html示例在开头主题部分Controller testing basics

4

1 回答 1

69

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

给定以下工厂:

FactoryGirl.define do
  factory :user do
    name 'John Doe'
  end
end

这是结果build

FactoryGirl.build :user
=> #<User id: nil, name: "John Doe", created_at: nil, updated_at: nil>

和结果attributes_for

FactoryGirl.attributes_for :user
=> {:name=>"John Doe"}

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

post :create, user: FactoryGirl.attributes_for(:user)

使用时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

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

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

于 2012-10-31T02:14:47.373 回答