在rails 3.1.0应用程序的rspec测试中,我们同时使用了Factory.build和Factory.attributes_for。我们发现,如果我们将Factory.build更改为Factory.attributes_for,则有一种数据验证失败。此外,Factory.attributes_for没有对其进行正确的测试。我想知道这两者之间的区别,以及如何在rspec中使用它们。
在我们的模型测试中,我们使用Factory.build。在更新或新的控制器测试中,我们使用Factory.attributes_for。我们刚刚在控制器测试中发现了一个案例,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控制器中的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由于验证失败,上面的控制器用例失败。控制器情况下的失败是由于在创建控制器rfqs时添加了以下行而导致的。
@rfq.report_language = nil unless params[:need_report]但是,rfq模型中的案例(见上面的rfq模型)已经成功通过。在模型测试中是.build,在控制器测试中是.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]不返回任何内容,并且不是从参数中检索数据的正确方法。
发布于 2012-01-26 14:09:27
Factory.attributes_for只返回Factory. Factory.build使用这些相同资产的属性的散列,但返回设置了这些相同属性的类的实例。
Factory.build(:user)在功能上等同于
User.new(Factory.attributes_for(:user))但是你会发现它们是不可互换的。也许如果你发布一些代码,我们可以更好地解释你的测试中发生了什么。
https://stackoverflow.com/questions/9014147
复制相似问题