如何使用无效的用户凭据实现RSpec会话控制器测试

时间:2015-02-17 23:02:47

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

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

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

非常感谢任何帮助。谢谢!

1 个答案:

答案 0 :(得分: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'))