【发布时间】:2017-11-03 22:54:18
【问题描述】:
我正在尝试使用 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
【问题讨论】:
-
完整的错误信息是什么,错误来自哪里?
-
@SebastiánPalma
get :show, id: @user.id -
尝试调试
auth_headers -
@LiroyLeshed.com
{"access-token"=>"Fb1PMNcGsW-eLN3idl0j2A", "token-type"=>"Bearer", "client"=>"YQtnU5BsYz9GX5VO1MJp_A", "expiry"=>"1510965716", "uid"=>"jailyn@king.co"} -
目前还想不通,不过用
type: :controller来测试岂不是更容易?
标签: ruby-on-rails ruby rspec