gpt4 book ai didi

ruby - Factory.build 和 Factory.attributes_for 有什么区别?

转载 作者:数据小太阳 更新时间:2023-10-29 08:28:41 25 4
gpt4 key购买 nike

在我们针对 rails 3.1.0 应用程序的 rspec 测试中,我们同时使用了 Factory.build 和 Factory.attributes_for。我们发现,如果我们将 Factory.build 更改为 Factory.attributes_for,则有一种情况是数据验证失败。此外 Factory.attributes_for 没有正确测试它。我想知道这两者之间有什么区别,以及如何在 rspec 中使用它们。

在我们的模型测试中,我们使用的是 Factory.build。在更新或新的 Controller 测试中,我们使用 Factory.attributes_for。我们刚刚在 Controller 测试中发现了一个案例,即 Factory.attributes_for 没有正确测试它并且没有通过 Factory.build 模型验证的案例。

非常感谢。

更新:这是 rfq 模型中的一个 rspec 案例:

  it "should not have nil in report_language if need_report is true" do
rfq = Factory.build(:rfq, :need_report => true, :report_language => nil)
rfq.should_not be_valid
end

这是 rfq Controller 中的一个 rspec 案例:

it "should be successful for corp head" do
session[:corp_head] = true
session[:user_id] = 1
s = Factory(:standard)
rfq = Factory.attributes_for(:rfq, :need_report => true, :report_language => 'EN')
rfq[:standard_ids] = [s.id] # attach standard_id's to mimic the POST'ed form data
get 'create', :rfq => rfq
response.should redirect_to URI.escape("/view_handler?index=0&msg=RFQ saved!")
end

由于验证失败,上述 Controller 案例失败。 Controller 案例中的失败是由于在创建 Controller 请求请求时添加了以下行。

  @rfq.report_language = nil unless params[:need_report]

但是 rfq 模型中的案例(参见上面的 rfq 模型)已经成功通过。在模型测试中是.build,在 Controller 测试中是.attributes_for。

更新:

正确的说法应该是:

@rfq.report_language = nil unless params[:rfq][:need_report] == 'true'

@rfq.report_language = nil if params[:rfq][:need_report] == 'false'

params[:need_report] 不返回任何内容,这不是从参数中检索数据的正确方法。

最佳答案

Factory.attributes_for 只是返回 Factory 的属性散列。 Factory.build 使用这些相同的 Assets ,但返回具有相同属性集的类实例。

Factory.build(:user)

在功能上等同于

User.new(Factory.attributes_for(:user))

但您会发现它们不可互换。也许如果您发布一些代码,我们可以更好地解释您的测试中发生了什么。

关于ruby - Factory.build 和 Factory.attributes_for 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9014147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com