这是我创建的脚手架生成的默认测试。
describe "PUT update", focus: true do
describe "with valid params" do
it "updates the requested purchase_order" do
current_valid_attr = valid_attributes
purchase_order = PurchaseOrder.create! current_valid_attr
# Assuming there are no other purchase_orders in the database, this
# specifies that the PurchaseOrder created on the previous line
# receives the :update_attributes message with whatever params are
# submitted in the request.
# PurchaseOrder.any_instance.should_receive(:update_attributes).with({'these' => 'params'})
# put :update, :id => purchase_order.id, :purchase_order => {'these' => 'params'}
PurchaseOrder.any_instance.should_receive(:update_attributes).with(current_valid_attr)
put :update, :id => purchase_order.id, :purchase_order => current_valid_attr
end
问题是我不明白它应该做什么而且我不能通过使用正确的属性。这是我运行测试时的错误
Failures:
1) PurchaseOrdersController PUT update with valid params updates the requested purchase_order
Failure/Error: put :update, :id => purchase_order.id, :purchase_order => current_valid_attr
#<PurchaseOrder:0x007fe3027521e0> received :update_attributes with unexpected arguments
expected: ({"id"=>nil, "supplier_id"=>1, "no"=>1305, "no_rujukan"=>"Guiseppe Abshire", "jenis"=>"P", "mula_on"=>Sat, 23 Aug 2003 14:11:42 MYT +08:00, "created_at"=>nil, "updated_at"=>nil})
got: ({"id"=>nil, "supplier_id"=>"1", "no"=>"1305", "no_rujukan"=>"Guiseppe Abshire", "jenis"=>"P", "mula_on"=>"2003-08-23 14:11:42 +0800", "created_at"=>nil, "updated_at"=>nil})
提前致谢。
valid_attributes
def valid_attributes
Factory.build(:purchase_order).attributes
end
工厂
FactoryGirl.define do
factory :purchase_order do
association :supplier
sequence(:no) { |n| Random.rand(1000...9999) }
sequence(:no_rujukan) { |n| Faker::Name.name }
sequence(:jenis) { |n| PurchaseOrder::PEROLEHAN[Random.rand(0..3).to_i] }
sequence(:mula_on) { |n| Random.rand(10.year).ago }
end
end
答案 0 :(得分:3)
此测试会检查当PurchaseOrdersController#update
update_attributes
某个PurchaseOrder
模型的update_attributes
操作String
方法的请求被调用时,请求参数会正确传递给此方法。
此处的问题(如错误消息所述)是使用具有类型params
的所有值的属性哈希调用update
。这是因为current_valid_attr
操作中最有可能使用的Fixnum
哈希值(包含所有请求参数)都是字符串。
另一方面,您的Time
哈希包含不同类型的值,例如no
和1305
。当比较预期值和接收值时,您会收到错误,因为,例如,update_attributes
属性应该是Fixnum '1305'
,但在提交请求后,它会转换为字符串并{{1收到字符串current_valid_attr
而不是。
解决问题的方法之一是确保no = 1305
mula_on = Time.now
# explicitly convert all attributes to String
current_valid_attr = { :no => no.to_s, :mula_on => mula_on.to_s }
中的所有值都是字符串:
params
<强>更新强>
可以在测试中使用paramify_values
方法将参数哈希转换为控制器在{{1}}哈希中接收的相同表单。