Rspec request specs and Rails 5

元气小坏坏 提交于 2019-12-21 04:51:12

问题


I'm starting a new project, my first with Rails 5.1.0. I have a pb with my first request spec.

describe 'Users', type: :request do
  it 'are created from external data' do
    json_string = File.read('path/to/test_data/user_data.json')
    params = { user: JSON.parse(json_string) }
    headers = { "CONTENT_TYPE" => "application/json" }

    expect do
      post '/api/v1/users', params.to_s, headers
    end.to change {
      User.count
    }.by(1)

    expect(response.status).to eq 200
  end
end

this spec return the error ArgumentError: wrong number of arguments (given 3, expected 1). The official documentation don't say much.

If I take out the .to_s, and send a hash, like this:

post '/api/v1/users', params, headers

I got another error:

ArgumentError: unknown keyword: user

Any thought?


回答1:


I think they changed the syntax recently. Now it should use keyword args. So, something like this:

post '/api/v1/users', params: params, headers: headers



回答2:


Here's a little addendum to Sergio's answer. If you are upgrading from Rails 4 to Rails 5, have lots of tests, and aren't too keen on changing them all – at least not until you've finished upgrading – I've found a way to make them work with the old method signature.

In my spec_helper I added

module FixLegacyTestRequests
  def get(path, par = {}, hdr = {})
    process(:get, path, params: par, headers: hdr)
  end
  def post(path, par = {}, hdr = {})
    process(:post, path, params: par, headers: hdr)
  end
  def put(path, par = {}, hdr = {})
    process(:put, path, params: par, headers: hdr)
  end
  def delete(path, par = {}, hdr = {})
    process(:delete, path, params: par, headers: hdr)
  end
end

and then I added this configuration for each test:

RSpec.configure do |config|
  config.before :each do |example|
    extend(FixLegacyTestRequests) # to be removed at some point!
  end
end

My tests went back to working, and I think it should be safe because it's only applied to the currently running test and shouldn't pollute any gem's code such as with a monkey patch.



来源:https://stackoverflow.com/questions/43412951/rspec-request-specs-and-rails-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!