use*_*363 2 ruby rspec2 factory-bot
在我们针对rails 3.1.0 app的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
Run Code Online (Sandbox Code Playgroud)
这是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
Run Code Online (Sandbox Code Playgroud)
由于验证失败,上述控制器案例失败.控制器情况的失败是由于下面的行添加到控制器rfqs的创建引起的.
@rfq.report_language = nil unless params[:need_report]
Run Code Online (Sandbox Code Playgroud)
但是rfq模型中的情况(参见上面的rfq模型)已成功通过.它是模型测试中的.build和控制器测试中的.attributes_for.
更新:
正确的陈述应该是:
@rfq.report_language = nil unless params[:rfq][:need_report] == 'true'
Run Code Online (Sandbox Code Playgroud)
要么
@rfq.report_language = nil if params[:rfq][:need_report] == 'false'
Run Code Online (Sandbox Code Playgroud)
params[:need_report]
什么都不返回,不是从params中检索数据的正确方法.
小智 6
Factory.attributes_for
只返回Factory. Factory.build
使用这些相同资产的属性的哈希值,但返回具有相同属性集的类的实例.
Factory.build(:user)
Run Code Online (Sandbox Code Playgroud)
在功能上等同于
User.new(Factory.attributes_for(:user))
Run Code Online (Sandbox Code Playgroud)
但你会发现它们不可互换.也许如果你发布一些代码,我们可以更好地解释你的测试中发生了什么.