简体   繁体   English

Rspec请求规范和Rails 5

[英]Rspec request specs and Rails 5

I'm starting a new project, my first with Rails 5.1.0. 我正在开始一个新项目,我的第一个使用Rails 5.1.0。 I have a pb with my first request spec. 我有一个pb与我的第一个请求规范。

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) . 此规范返回错误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: 如果我取出.to_s,并发送一个哈希,如下所示:

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

I got another error: 我有另一个错误:

ArgumentError: unknown keyword: user

Any thought? 任何想法?

I think they changed the syntax recently. 我认为他们最近改变了语法。 Now it should use keyword args. 现在它应该使用关键字args。 So, something like this: 所以,像这样:

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

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. 如果你从Rails 4升级到Rails 5,有很多测试,并且不太热衷于更改它们 - 至少在你完成升级之前 - 我已经找到了一种方法让它们能够与旧的一起工作方法签名。

In my spec_helper I added 在我的spec_helper我补充道

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. 我的测试又恢复了工作,我认为它应该是安全的,因为它只适用于当前运行的测试,不应该污染任何gem代码,例如使用猴子补丁。

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

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