【问题标题】:How to implement RSpec session controller test with invalid user credentials如何使用无效的用户凭据实现 RSpec 会话控制器测试
【发布时间】:2015-02-17 23:02:46
【问题描述】:

我正在为我的SessionsController 编写 RSpec 测试。在使用 valid 凭据测试 session#create 时,我的测试工作正常。但是,我还想为用户凭据无效时发生的情况编写测试,例如重定向回登录页面、设置闪光警报等。但是对于任何这些测试,我出现错误:

1) SessionsController POST #create when password is INCORRECT
  Failure/Error: post :create, user: {username: 'Example', password: ''}
  ArgumentError:
    uncaught throw :warden
  # ./spec/support/default_params.rb:7:in `process_with_default_params'
  # ./spec/controllers/sessions_controller_spec.rb:24:in `block (4 levels) in <top (required)>'

这是我的sessions_controller_spec.rb 代码:

require 'spec_helper'

describe SessionsController do
  before do
    @request.env["devise.mapping"] = Devise.mappings[:user]
  end

  describe 'POST #create' do
    context "when password is INCORRECT" do
      let!(:user) { FactoryGirl.create(:user, username: 'Example', password: 'Secr3t&$') }

      before(:each) do
        post :create, user: { username: 'Example', password: '' }
      end

      it { should set_the_flash[:alert].to('Invalid username or password.') }
      it { should respond_with(:redirect) }
      it { should redirect_to(:new_user_session) }
  end
end

这是我的spec_helper.rb 代码:

RSpec.configure do |config|
  config.include Devise::TestHelpers, type: :controller
end

任何帮助将不胜感激。谢谢!

【问题讨论】:

  • 您能否再次检查它是否也包含在测试中?根据您的 spec_helper,我知道它应该,但我记得至少有一次它没有像您期望的那样自动连接到我。
  • 这里也有类似的问题:stackoverflow.com/a/17541915/3507417

标签: ruby-on-rails authentication rspec devise tdd


【解决方案1】:

我知道现在为时已晚,但万一这对其他人有帮助:您需要将 setup_controller_for_warden 添加到您的 before 块中,因此它变为:

before do
  @request.env["devise.mapping"] = Devise.mappings[:user]
  setup_controller_for_warden
end

另外,最好使用翻译为您断言。在 rspec 3 格式中,断言应该是这样的:

expect(flash[:alert]).to eq(I18n.t('devise.failure.invalid'))

【讨论】:

  • 感谢正确的 I18n 检查。如果您使用自定义身份验证密钥,则可以对其进行参数化:expect(flash[:alert]).to eq(I18n.t('devise.failure.invalid', authentication_keys: 'Login'))
猜你喜欢
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多