通过浏览控制器测试教程,作者给出了一个rspec测试控制器动作的示例.我的问题是,为什么他们使用attributes_forbuild的方法?除了返回一个散列值之外,没有明确的解释为什么使用attributes_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节找到

推荐答案

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当我直接想要对象而不是属性散列时

如果你需要更多细节,请告诉我

Ruby-on-rails相关问答推荐

`heroku Open`和`heroku run rake db:Migrate`不工作(";没有这样的文件或目录";)

合成轨道布局

如何通过graphqlMutations 从rails销毁当前用户会话

仅在两个子域间共享Rails cookies,并为所有其他子域使用单独的cookie

Rails 7 共享刺激控制器功能

ruby on rails 中的自定义关联

如何为 I18n 设置 raise_on_missing_translations

Mongoid 3 + Heroku (MongoHQ) 导致 Moped::Errors::OperationFailure

Ruby的自动代码质量工具?

安装mysql2(0.4.8)时出错,Bundler无法继续

Rails:设计:按角色登录后重定向

Ruby如何写入Tempfile

在两个 DateTime 之间迭代,步长为一小时

在 PostgreSQL 中强制字符串的最大长度

如何在Ruby 中对数字进行上限和舍入

导轨链接到:远程

Rails 控制台中手动更新属性值的验证问题

如何在同一个 Rails 控制器操作中处理多个 HTTP 方法

Rspec - Rails - 如何遵循重定向

是否可以设置 travis 来运行多种语言的测试?