NoMethodError:nil的未定义方法`env':NilClass

时间:2014-12-26 08:38:39

标签: ruby-on-rails rspec

我想测试我的控制器posts,当我运行Rspec测试时,shell会显示错误

 Failure/Error: Unable to find matching line from backtrace
 NoMethodError:
   undefined method `env' for nil:NilClass
 # /home/weare138/.rvm/gems/ruby-2.1.5/gems/devise-3.4.1/lib/devise/test_helpers.rb:24:in `setup_controller_for_warden'

这是我的spec/requests/posts_spec.rb

require 'rails_helper'

describe "Posts" do
  describe "GET /posts" do
    it "works! (now write some real specs)" do
      user = FactoryGirl.create(:user, role: 'admin')
      sign_in user
    end
  end
end

UPD

rails_helper

ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.include Devise::TestHelpers, :type => :request
  config.use_transactional_fixtures = true
  config.infer_spec_type_from_file_location!
end

如何解决?

2 个答案:

答案 0 :(得分:0)

这是Devise :: TestHlepers的问题,因为它可以从stacktrace中看到。

重复this question(也检查相关问题)。

答案 1 :(得分:0)

尽管问题已经很久了,但这是请求规范的解决方案。尝试使用:

config.include Devise::Test::IntegrationHelpers, type: :request

代替

config.include Devise::Test::ControllerHelpers, type: :request