Rspec Rails控制器提交表格参数URI编码而不是哈希

时间:2015-12-09 19:31:05

标签: ruby-on-rails ruby rspec controller

我正在测试控制器,当我提交表单数据时,其中一些作为字符串进入控制器,而不是我期望的哈希值。

def send_request(params={})
  patch :update, params.merge(:id => @company.id)
end

describe 'should_receive' do
  let(:test_params) do
    {
      "utf8"=>"✓",
      "_method"=>"patch",
      "button"=>"",
      "company"=>
      { "label_ids"=>[""],
        "customer_users_attributes"=>{"0"=>{"id"=>"3", "is_primary"=>"true"}},
        "baselines_attributes"=>{"0"=>{"label_ids"=>[""], "benchmark_ids"=>[""], "id"=>"1"}}},
      "action"=>"update",
      "controller"=>"admin/companies",
    }
  end

  after(:each) do
    send_request(test_params)
  end

  it { @company.should_receive(:update).with(test_params).and_return(true) }

运行测试时的错误:

 Failure/Error: patch :update, params.merge(:id => @company.id)
 NoMethodError:
   undefined method `has_key?' for "baselines_attributes%5Bsite_url%5D=site_url":String

失败前的参数:

{"utf8"=>"✓",
 "_method"=>"patch",
 "button"=>"",
 "company"=>
  "baselines_attributes%5B0%5D%5Bbenchmark_ids%5D%5B%5D=&baselines_attributes%5B0%5D%5Bid%5D=1&baselines_attributes%5B0%5D%5Blabel_ids%5D%5B%5D=&customer_users_attributes%5B0%5D%5Bid%5D=3&customer_users_attributes%5B0%5D%5Bis_primary%5D=true&label_ids%5B%5D=",
 "action"=>"update",
 "controller"=>"admin/companies",
 "id"=>"1"}

通过浏览器提交表单时位于同一位置的参数:

{"utf8"=>"✓",
 "_method"=>"patch",
 "button"=>"",
 "company"=>
  {"label_ids"=>[""],
   "customer_users_attributes"=>{"0"=>{"id"=>"3",
     "is_primary"=>"true"}},
   "baselines_attributes"=>{
     "0"=>{"label_ids"=>[""], "benchmark_ids"=>[""], "id"=>"1"}}},
 "action"=>"update",
 "controller"=>"admin/companies",
 "id"=>"1"}

在测试中,params [:company]中的所有内容都是URI编码的字符串,而在实际代码中,它恰当地作为哈希值。

如何正确处理测试数据?

更新

Ruby 2.2.0

相关宝石:

  • rails(4.0.13)
  • rspec-core(2.14.8)
  • nested_form(0.3.2)

1 个答案:

答案 0 :(得分:0)

为什么不使用FactoryGirl来构建属性?