Rspec 3.未定义的局部变量或方法`response’for#

我想用rspec测试API控制器。 所以这是一段简单的代码:

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 

但我有一个错误:

 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 # # ./spec/routing/api/v1/devise/configs_routing_spec.rb:13:in `block (3 levels) in ' 

RSpec 3你会做:

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

您的控制器规格是否在specs / controller目录中? 如果没有,则Rspec需要您通过使用元数据标记describe来明确声明它们是控制器规范:type => :controller这是因为response变量仅在您的规范设置为控制器规范时可用,即

 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 

另外看看这里

您可以尝试使用此语法

 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 

使用expect(last_response.status).to be(200)而不是仅响应

这个对我有用!

仅供参考:我正在使用rails 5