Rspec 3. undefined local variable or method `response' for #<RSpec::ExampleGroups::ConfigsAPI::GETApiConfig:0x007f84d93fbb90>

给你一囗甜甜゛ 提交于 2019-12-12 10:05:52

问题


I want to test API controller with rspec. So here is the simple piece of code:

require 'rails_helper'  
describe "GET /api/config" do

  it 'routes GET to /api/config to Api::V1::ConfigsController#show' do
    get '/api/config.json'
    expect(response).to be_success
  end

end

But I've got an error:

1) Configs API GET /api/config routes GET to /api/config to Api::V1::ConfigsController#show
     Failure/Error: expect(response).to be_success
     NameError:
       undefined local variable or method `response' for #<RSpec::ExampleGroups::ConfigsAPI::GETApiConfig:0x007f84d93fbb90>
     # ./spec/routing/api/v1/devise/configs_routing_spec.rb:13:in `block (3 levels) in <top (required)>'

回答1:


In RSpec 3 you would do:

get '/api/config.json'
expect(response.status).to be(200)

What you're missing is a type declaration in your describe block, ie:

describe "GET /api/config", type: :controller do
end



回答2:


Are your controller specs in the specs/controller directory? If not, then Rspec needs you to explicitly declare that they are controller specs by tagging the describe with the metadata :type => :controller This is because the response variable is available only when your spec is set up as a controller spec i.e

require 'rails_helper'  
describe "GET /api/config", type: :controller do

  it 'routes GET to /api/config to Api::V1::ConfigsController#show' do
    get '/api/config.json'
    expect(response).to be_success
  end

end

Also take a look here




回答3:


You can try for this syntax

describe "GET /api/config", type: :controller do

  it 'routes GET to /api/config to Api::V1::ConfigsController#show' do
    get '/api/config.json'
    expect(last_response.status).to be(200)
  end

end

Use expect(last_response.status).to be(200) instead of only response

It works for me!

FYI: I am using rails 5



来源:https://stackoverflow.com/questions/24776069/rspec-3-undefined-local-variable-or-method-response-for-rspecexamplegroup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!