在rspec特性测试中使用Devise

时间:2015-09-17 10:27:13

标签: ruby-on-rails testing rspec devise

我编写了以下rspec功能测试规范:

require "rails_helper"

RSpec.describe "Team management", type: :feature do
  user_sign_in

  describe "User creates a new team" do
    ...    
    expect(page).to have_link("#{team_name}")
  end
end

我的user_sign_in

中定义了rails_helper.rb方法
ENV['RAILS_ENV'] ||= 'test'
require 'spec_helper'
require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
require 'capybara/rails'

...

module UserSignInHelpers
  def user_sign_in
    before(:each) do
      @request.env['devise.mapping'] = Devise.mappings[:user]

      @current_user = FactoryGirl.create(:user)
      @current_user.confirm

      sign_in :user, @current_user
    end
  end
end

RSpec.configure do |config|
  ...
  # The different available types are documented in the features, such as in
  # https://relishapp.com/rspec/rspec-rails/docs
  config.infer_spec_type_from_file_location!

  config.extend UserSignInHelpers,    type: :controller
  config.extend UserSignInHelpers,    type: :feature
  config.include Devise::TestHelpers, type: :controller
  config.include Devise::TestHelpers, type: :feature
end

user_sign_in方法适用于我的所有控制器规范,但是当我运行我的功能规范时,它失败了:

Team management
  User creates a new team
    example at ./spec/features/user_creates_a_new_team_spec.rb:19 (FAILED - 1)

Failures:

  1) Team management User creates a new team
     Failure/Error: Unable to find matching line from backtrace
     NoMethodError:
       undefined method `env' for nil:NilClass
     # /Users/xxxx/.rvm/gems/ruby-2.2.1/gems/devise-3.5.1/lib/devise/test_helpers.rb:24:in `setup_controller_for_warden'

我不明白为什么这适用于控制器测试而不是功能测试。我能做些什么让它在功能测试中起作用吗?

1 个答案:

答案 0 :(得分:2)

  

您尝试做的事情存在一个基本问题。 (DeviseWarden之上的Warden工作是一个   Rack中间件,但RSpec控制器规格甚至不包含Rack,   因为这些类型的规范并不意味着运行您的完整应用程序   堆栈,但只有您的控制器代码。

Ref

Test with Capybara

我有一个简单的支持助手,允许我登录和注销用户:

module Auth
  def create_user!
    @user = User.create(email: 'foo@bar.com', password: '11111111')
  end

  def sign_in_user!
    setup_devise_mapping!
    sign_in @user
  end

  def sign_out_user!
    setup_devise_mapping!
    sign_out @user
  end

  def setup_devise_mapping!
    @request.env["devise.mapping"] = Devise.mappings[:user]
  end

  def login_with_warden!
    login_as(@user, scope: :user)
  end

  def logout_with_warden!
    logout(:user)
  end

  def login_and_logout_with_devise
    sign_in_user!
    yield
    sign_out_user!
  end

  def login_and_logout_with_warden
    Warden.test_mode!
    login_with_warden!
    yield
    logout_with_warden!
    Warden.test_reset!
  end
end

在一个功能中:

RSpec.describe "Team management", type: :feature do
  describe "User creates a new team" do
     login_and_logout_with_warden do
       # tests goes here
     end
  end
end

在控制器中:

RSpec.describe "Team management", type: :controller do
  describe "User creates a new team" do
    login_and_logout_with_devise do
      # tests goes here
    end
  end
end