我想用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 #<RSpec::ExampleGroups::ConfigsAPI::GETApiConfig:0x007f84d93fbb90>
# ./spec/routing/api/v1/devise/configs_routing_spec.rb:13:in `block (3 levels) in <top (required)>'
答案 0 :(得分:2)
在RSpec 3
你会做:
get '/api/config.json'
expect(response.status).to be(200)
答案 1 :(得分:1)
您的控制器规格是否在specs / controller目录中?如果没有,那么Rspec需要您通过使用元数据: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
另请查看here
答案 2 :(得分:0)
您可以尝试使用此语法
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