Antarr Byrd
Antarr Byrd

Reputation: 26061

Rails Controller Spec. Wrong number of arguments

I'm trying to test my controller using RSpec but I'm getting the error below.

error

  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)>'

spec

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'=>'[email protected]'})
    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  

Upvotes: 1

Views: 1191

Answers (1)

Alex Freshmann
Alex Freshmann

Reputation: 481

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

must be

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

OR (and it will be more suitable for api test)

you can rewrite this

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

to this

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

Upvotes: 1

Related Questions