测试未经身份验证的用户Rspec / Devise

时间:2014-06-20 07:53:17

标签: ruby-on-rails ruby rspec devise

我环顾四周,但也许我没有找到合适的地方。我试图找出如何测试用户无法访问控制器具有的页面

before_filter :authenticate_user!

理想情况下,我想同时捕获设计信息

"you need to sign in or sign up before continuing"

到目前为止我有这个

require 'spec_helper'

describe CampaignsController do

  it "should not allow a user be able to access without being authenticated" do
    get :index
    response.should redirect_to(new_user_session_path)
  end

目前我收到错误

Failure/Error: response.should redirect_to(new_user_session_path)
Expected response to be a <redirect>, but was <200>

广告系列控制器

class CampaignsController < ApplicationController
  before_filter :authenticate_user! 

def index
  @campaigns = Campaign.all
end
end

在我的规范助手中,我打电话给以下

# Include Devise Test Helpers
config.include Devise::TestHelpers, :type => :controller
config.extend ControllerMacros, :type => :controller

controller_macros.rb

module ControllerMacros

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

我没有在这个阶段调用login_user方法,那么spec_helper会调用它吗?

我如何正确处理此问题

任何帮助表示赞赏

由于

2 个答案:

答案 0 :(得分:2)

起初看起来似乎没问题。如果您运行整个套件,可能会导致此问题,并且根据您拨打login_user的位置,可能会将before(:each)添加到所有测试中。

我知道您希望尽量减少打字,但通常我更喜欢我的测试更明确一些:我想看看规范中发生了什么。

所以我通常会写这种测试:

describe HomeController do
  include Devise::TestHelpers

  context "when not signed in" do
    describe "GET 'index'" do
      it "redirects to sign in" do
        get 'index'
        response.should be_redirect
      end
    end
    describe "GET 'about'" do
      it "returns http success" do
        get 'about'
        response.should be_redirect
      end
    end
  end

  context "when signed in" do
    before do
      user = FactoryGirl.create(:user)
      sign_in(user)
    end
    describe 'GET :index' do
      it "returns http success" do
        get 'index'
        response.should be_success
      end
    end
    describe "GET 'about'" do
      it "returns http success" do
        get 'about'
        response.should be_success
      end
    end
  end
end

是的,承认:我仍然喜欢旧的rspec语法(使用should),它对我来说更自然。

答案 1 :(得分:0)

请尝试

module ControllerMacros

  def login_user
    @request.env["devise.mapping"] = Devise.mappings[:user]
    user = FactoryGirl.create(:user)
    sign_in user
  end
end
rspec文件中的

require 'spec_helper'

describe CampaignsController do

  it 'for authenticate user' do
    before do
      login user
    end
  end

  it "should not allow a user be able to access without being authenticated" do
    get :index
    expect(response).to redirect_to(new_user_session_path)
  end