简体   繁体   English

如何修复“没有将字符串隐式转换为哈希”

[英]How to fix "no implicit conversion of String into Hash"

I am trying to run a test with RSpec but it always returns the same error:我正在尝试使用 RSpec 运行测试,但它总是返回相同的错误:

DevicesController#update when user is a manager must update any device
     Failure/Error: put device_path device_id, params: params, headers: { 'Content-Type': 'application/vnd.api+json' }

     TypeError:
       no implicit conversion of String into Hash

My function with the request params:我的请求参数函数:

def update_params(device, device_id)
  {
    data: {
      id: device.id,
      type: 'device',
      attributes: {
        device_id: device_id 
      }
    }
  }.to_json
end

My test using factories:我使用工厂的测试:

context 'when user is a manager' do
  let(:user) { create(:manager).account }
  let(:firebase_token) { Faker::Crypto.sha1 }
  let(:device_id) { physical_device.id }
  let(:params) { update_params(physical_device, firebase_token) }
  it 'must update any device' do
    expect(Device.find(device_id).device_id).to eq(firebase_token)
  end
end

The request OS update device:请求操作系统更新设备:

put device_path device_id, params: params, headers: { 'Content-Type': 'application/vnd.api+json' }

ActionController::TestCase expects the params to be a hash (like the headers ). ActionController::TestCase期望params是一个哈希值(就像headers )。

But the params you pass to this method callparams传递给这个方法调用

put device_path device_id, params: params, headers: { 'Content-Type': 'application/vnd.api+json' }

are generated by the update_params method and that method calls to_json on the generated hash and therefore returns a JSON string .update_params方法生成,该方法对生成的哈希调用to_json ,因此返回一个 JSON字符串

Just remove the .to_json from the last line of the update_params method and you should be fine.只需从update_params方法的最后一行中删除.to_json就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM