8

This is a spec for a very typical controller with a before_filter which redirects to login page when a not-logged-in user (a.k.a. a guest) tries to access /projects/new.

describe ProjectsController do
  (...)

  describe "GET new" do
    context 'when not logged in' do
      before { sign_in_nobody }

      context 'creating project' do
        before { get :new }

        it 'denies access' do
          expect(response).to be_redirect
        end
      end
    end
  end
end

I have specced all possible outcomes of accessing :index, :show and :new for guests, users, admins and superadmins. I didn't have any problems using neither logged or guest users, admins or not – but this is actually the first time this spec touched an action that involves Devise's before_filter :autheticate_user! and it fails miserably at that.

As you might already suspect – the spec doesn't even reach expect(response).to be_redirect, it throws a hissy fit before:

Failures:

1) ProjectsController GET new when not logged in creating project denies access
   Failure/Error: get :new
   ArgumentError:
     uncaught throw :warden
   # ./spec/controllers/projects_controller_spec.rb:344:in `block (5 levels) in <top (required)>'

I've searched for an answer to question: "how to properly test for unauthenticated (guest) users with rspec and devise", but everyone only talks about having problem with actually logging users in devise for RSpec to use. A problem which I solved thusly:

#spec/support/devise_authenticators.rb
include Devise::TestHelpers

def sign_in_nobody
  @request.env["devise.mapping"] = Devise.mappings[:user]
  sign_in User.new
end

def sign_in_user
  @request.env["devise.mapping"] = Devise.mappings[:user]
  sign_in FactoryGirl.create(:user)
end

However it's not the logging in that fails here, it's the "being not logged". So far I got absolutely nothing and I know people HAVE to test those scenarios somehow.

Right now I'm using a walkaround:

before { sign_in_nobody }

context 'creating project' do
  it 'denies access' do
    expect{ get :new }.to raise_exception("uncaught throw :warden")
  end
end

But even tho it's practically correct (uncaught throw :warden happens only when authenticate_user! fails so it can be used as an expectation) in theory it feels really dirty.

Any ideas how to do it properly?

(...Maybe I shouldn't be testing this at all, seeing as how the correctness of before_filter authenticate_user! is Devise's responsibility not mine?)

4

3 回答 3

4

应该可以工作。我只是花了一段时间来解决同样的问题,结果发现我们有一个测试助手可以覆盖process控制器测试。设计也覆盖它,catch :warden所以我只需要include Devise::TestHelpers在包含默认参数模块之前。

有关我说我们覆盖时所说的示例process,请参阅此答案,该答案描述了如何设置默认参数以包含format: json

于 2013-11-05T20:46:33.410 回答
1

我有一个类似的问题,我是这样解决的:

e = catch(:warden) { get root_url }
expect(e[:message]).to be(:not_activated)
于 2017-02-06T12:41:58.103 回答
1

所以教训是失败uncaught throw :warden时会发生这种情况。authenticate_user!

所以找出你的用户身份验证失败的原因,你就会解决你的问题。

于 2016-02-23T13:14:35.343 回答