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