Rails控制器规格参数数量错误

时间:2017-11-03 22:54:19

标签: ruby-on-rails ruby rspec

我正在尝试使用RSpec测试我的控制器,但我收到以下错误。

错误

  1) Api::V1::UsersController GET #show responds with 200 status code
     Failure/Error: request.headers.merge!(auth_headers)

     ArgumentError:
       wrong number of arguments (given 0, expected 1..2)
     # ./spec/controllers/api/v1/users_controller_spec.rb:9:in `block (3 levels) in <top (required)>'

  2) Api::V1::UsersController GET #show returns the serialized user attributes
     Failure/Error: request.headers.merge!(auth_headers)

     ArgumentError:
       wrong number of arguments (given 0, expected 1..2)
     # ./spec/controllers/api/v1/users_controller_spec.rb:9:in `block (3 levels) in <top (required)>'

规范

require 'spec_helper'

describe Api::V1::UsersController, type: :api do

  describe 'GET #show' do
    before(:each) do
      @user = FactoryBot.create :user
      auth_headers = @user.create_new_auth_token
      request.headers.merge!(auth_headers)
      get :show, id: @user.id
    end

    it 'responds with 200 status code' do
      expect(response.code).to eq('200')
    end

    it 'returns the serialized user attributes' do
      expect(json['data']['attributes']).to eq({'name'=>'John Doe', 'email'=>'test@test.com'})
    end
  end

end

spec_helper

require File.expand_path("../../config/environment", __FILE__)
Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f}


RSpec.configure do |config|
  config.include ApiHelper, type: :api
  config.include Requests::JsonHelpers, type: :api

  config.include FactoryBot::Syntax::Methods
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  # rspec-mocks config goes here. You can use an alternate test double
  # library (such as bogus or mocha) by changing the `mock_with` option here.
  config.mock_with :rspec do |mocks|
    mocks.verify_partial_doubles = true
  end
  config.shared_context_metadata_behavior = :apply_to_host_groups
end

api_helper.rb

module ApiHelper
  include Rack::Test::Methods

  def app
    Rails.application
  end
end  

request_helper.rb

module Requests
  module JsonHelpers
    def json
      JSON.parse(last_response.body)
    end
  end
end  

1 个答案:

答案 0 :(得分:1)

describe Api::V1::UsersController, type: :controller

必须是

auth_headers = @user.create_new_auth_token request.headers.merge!(auth_headers) get :show, id: @user.id

OR (它更适合api测试)

你可以改写这个

auth_headers = { 'AUTHORIZATION' => "Token #{@user.create_new_auth_token}" }
get :show, { id: @user.id }, auth_headers

到这个

table_ref.view_query = sqlQuery
table_ref.view_use_legacy_sql = True