澄清这个默认的rspec控制器测试并使其通过

时间:2011-12-24 05:20:04

标签: testing rspec ruby-on-rails-3.1

这是我创建的脚手架生成的默认测试。

  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

1 个答案:

答案 0 :(得分:3)

此测试会检查当PurchaseOrdersController#update update_attributes某个PurchaseOrder模型的update_attributes操作String方法的请求被调用时,请求参数会正确传递给此方法。

此处的问题(如错误消息所述)是使用具有类型params的所有值的属性哈希调用update。这是因为current_valid_attr操作中最有可能使用的Fixnum哈希值(包含所有请求参数)都是字符串。

另一方面,您的Time哈希包含不同类型的值,例如no1305。当比较预期值和接收值时,您会收到错误,因为,例如,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}}哈希中接收的相同表单。