【问题标题】:Rspec 3. undefined local variable or method `response' for #<RSpec::ExampleGroups::ConfigsAPI::GETApiConfig:0x007f84d93fbb90>Rspec 3. #<RSpec::ExampleGroups::ConfigsAPI::GETApiConfig:0x007f84d93fbb90> 的未定义局部变量或方法“响应”
【发布时间】:2014-07-16 08:39:42
【问题描述】:

我想用 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)>'

【问题讨论】:

  • 不确定,但您可以尝试将 type 添加到测试中。例如it 'routes GET ...', :type =&gt; :request do

标签: ruby-on-rails ruby rspec rspec3


【解决方案1】:

RSpec 3 你会这样做:

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

您缺少的是描述块中的类型声明,即:

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

【讨论】:

  • 它对谁起作用?调用未定义变量的方法是如何定义的?
  • @Nakilon 我不确定我明白你在问什么
  • 在 OP 的问题中,问题出在undefined 'response'。你仍然引用这个变量。向它附加另一个方法调用如何使其成为defined
  • 嗯,这个问题已经 3 个月大了 - 我想他在我回答时编辑了几次。最后,我们让它工作了
  • 它从未被编辑过..(我只是想了解这个 Rspec Rails 行为。
【解决方案2】:

您的控制器规格在 specs/controller 目录中吗?如果不是,则 Rspec 需要您通过使用元数据 :type =&gt; :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

【讨论】:

  • 如何将“response”变量添加到“api”规范(vs 控制器)中,以便所有“如何测试 api”示例都可以运行?必须是包含的特定库?(包括 Rack::Test::Methods 似乎没有这样做)。
【解决方案3】:

你可以试试这个语法

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多