Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rspec request specs and Rails 5

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?

like image 211
Ruff9 Avatar asked Apr 14 '17 13:04

Ruff9


2 Answers

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
like image 171
Sergio Tulentsev Avatar answered Sep 20 '22 08:09

Sergio Tulentsev


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.

like image 24
wiz Avatar answered Sep 19 '22 08:09

wiz