如何在 Rails 3.1.0 中以多对多方式 rspec 连接记录
这是 rfq 控制器中的创建:
def create
if has_create_right?
@rfq = Rfq.new(params[:rfq], :as => :roles_new )
#save into join table rfqs_standards
params[:rfq][:standard_ids].each do |sid|
@rfq.standards << Standard.find(sid.to_i) if !sid.nil?
end
if @rfq.save
redirect_to URI.escape("/view_handler?index=0&msg=RFQ saved!")
else
flash.now[:error] = "RFQ not saved!"
render 'new'
end
end
end
这是 rspec 代码
describe "'create'" do
it "should be successful for corp head" do
session[:corp_head] = true
session[:user_id] = 1
s = Factory(:standard)
rfq = Factory.attributes_for(:rfq)
rfq.standards << s
get 'create', :rfq => rfq
response.should redirect_to URI.escape("/view_handler?index=0&msg=RFQ saved!")
end
end
错误是:
1) RfqsController 'create' should be successful for corp head
Failure/Error: rfq.standards << s
NoMethodError:
undefined method `standards' for #<Hash:0x6741570>
# ./spec/controllers/rfqs_controller_spec.rb:65:in `block (3 levels) in <top (requi
测试连接记录的正确方法是什么?谢谢。
Here is the create in rfq controller:
def create
if has_create_right?
@rfq = Rfq.new(params[:rfq], :as => :roles_new )
#save into join table rfqs_standards
params[:rfq][:standard_ids].each do |sid|
@rfq.standards << Standard.find(sid.to_i) if !sid.nil?
end
if @rfq.save
redirect_to URI.escape("/view_handler?index=0&msg=RFQ saved!")
else
flash.now[:error] = "RFQ not saved!"
render 'new'
end
end
end
Here is the rspec code
describe "'create'" do
it "should be successful for corp head" do
session[:corp_head] = true
session[:user_id] = 1
s = Factory(:standard)
rfq = Factory.attributes_for(:rfq)
rfq.standards << s
get 'create', :rfq => rfq
response.should redirect_to URI.escape("/view_handler?index=0&msg=RFQ saved!")
end
end
The error is:
1) RfqsController 'create' should be successful for corp head
Failure/Error: rfq.standards << s
NoMethodError:
undefined method `standards' for #<Hash:0x6741570>
# ./spec/controllers/rfqs_controller_spec.rb:65:in `block (3 levels) in <top (requi
What's the right way to test join record? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从测试的这一部分来看:
rfq 似乎是作为属性哈希创建的,而不是完整的模型。您可以尝试像这样加入 standard_ids:
但是,似乎您可以使用嵌套属性完成所有这些 - 请参阅 http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
From this part of your test:
it would seem that rfq is created as an attributes hash and not a complete model. You can try joining the standard_ids like this:
However, it seems that you can accomplish all of this using nested attributes - see http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html