【问题标题】:Rspec Rails controller submit form params URI encoded rather than hashRspec Rails 控制器提交表单参数 URI 编码而不是哈希
【发布时间】:2023-03-07 04:16:01
【问题描述】:

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

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

相关宝石:

  • 导轨 (4.0.13)
  • rspec-core (2.14.8)
  • nested_form (0.3.2)

【问题讨论】:

  • 你能发布你的标记吗?你在用simple_form吗?
  • 我认为发布标记会分散注意力,但我会添加有关宝石/版本的详细信息。代码工作正常,问题出在测试上。

标签: ruby-on-rails ruby rspec controller


【解决方案1】:

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

【讨论】:

  • 我们在其他地方使用FactoryGirl,但我没有编写测试。我的猜测是作者只是在测试简单的功能,并不想构建一整套对象来测试它。 FactoryGirl 将如何提供帮助?
猜你喜欢
  • 2011-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多