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
- 在第一次失败时停止执行特定的rspec测试(不是测试套件)
- RSpec找不到我的命名路线
- 在RSpec 2中使用OR的平等
- 使用Rspec测试“Post create”
- ActiveRecord :: Base的未定义方法`mass_assignment_sanitizer =’:Class(NoMethodError)
- 为什么Rails实例方法可以用作rspec中的类方法
- 臭名昭着的AbstractController :: ActionNotFound – Devise + Rails
- 过滤链停止为:doorkeeper_authorize! 渲染或重定向
- 使用RSpec 3和Rails 4在控制器测试中查找新创建的记录