名称错误:未定义本地变量或方法“app”

9
我创建的控制器规范出现以下错误信息:

我创建的控制器规范出现以下错误信息:

NameError: undefined local variable or method `app' for \
  #<RSpec::Core::ExampleGroup::Nested_1::Nested_1::Nested_1:0x00000004424880>

...

# spec/controllers/sessions_conroller_spec.rb
require 'spec_helper'

describe SessionsController do

  before do
    @user = User.gen!
  end

  describe "#create" do
    context "when sending valid email and password" do
      it "renders a json hash ..." do
        post :create, email: @user.email, password: @user.password
        expect(last_response.status).to eq(201)
      end
    end
  end

  describe "#destroy" do
    context "when sending valid email and authentication token" do
      it "renders a json hash ..." do
        delete :destroy, email: @user.email, auth_token: @user.authentication_token
        expect(last_response.status).to eq(200)
      end
    end
  end

end

spec_helper.rb加载了一些混合。

ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'rspec/autorun'
require 'capybara/rspec'
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
  config.include Rack::Test::Methods, type: :controller
  config.fixture_path = "#{::Rails.root}/spec/fixtures"    
  config.use_transactional_fixtures = true
  config.infer_base_class_for_anonymous_controllers = false
  config.order = "random"
end

1
这可能会有用:https://www.ruby-forum.com/topic/1068659 - vee
然后我就无法访问last_response了。但你是对的:当我使用response时,第一个测试通过。然而,“destroy”操作测试失败:“期望值:200 实际值:401”,但这可能与身份验证令牌有关。我想知道如何定义app... - JJD
1
这个应该解决了吧?https://gist.github.com/alex-zige/5795358(用于API范围的Rake :: Test :: Methods的自定义Rspec Helper。) - vee
我可能会工作,但是API测试真的离控制器测试的常规约定有那么远吗? - JJD
2个回答

10

我没有像Jeremy所说的那样进行配置,但仍然遇到了错误。

我通过将以下内容添加到rails_helper.rb文件中来解决问题。

  def app
    Rails.application
  end

但我不确定为什么现在它能工作,有什么想法吗?

8
请从您的spec_helper.rb中删除以下内容。
config.include Rack::Test::Methods, type: :controller

对于其他人遇到“NameError: undefined local variable or method `app'”错误而感到头疼的情况,当您一次运行所有测试(多个文件)并且其中一个文件使用了include Rack::Test::Methods时,也会发生这种情况-包含“感染”了其他测试。因此,症状是当单独运行文件时,所有测试都通过,但是当它们一起运行时,它们会失败并显示“no app”错误。至少在rails 3.0.9rspec 3.0中会出现这种情况。 - Nico Brenner
@NicoBrenner 这是我的情况,我遇到了这个问题。你是如何解决的?谢谢! - Victor
@NicoBrenner 这是我的情况,我遇到了这个问题。你是如何解决的?谢谢! - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接