0

我正在为项目的管理部分创建一个基本控制器。管理部分的所有控制器都将从它继承。

#app/controllers/admins/base_controller.rb

class Admins::BaseController < ApplicationController
  layout "admin_cms"
  before_filter :authenticate_admin!
end

-

#spec/controllers/admins/base_controller_spec.rb

require 'spec_helper'

describe Admins::BaseController do
  controller do
    def index
    end
  end

  describe "before_filter#authenticate_admin!" do
    before(:each) do
      @admin = FactoryGirl.create(:admin)
      @request.env["devise.mapping"] = Devise.mappings[:admin]
    end

    context "when admin is not logged in" do
      it "redirect admin to sign_in path" do
        get :index
        response.should redirect_to new_admin_session_path
      end
    end

  end
end

我已经在我的 spec_helper.rb 中包含了 Devise::TestHelpers 并且在运行此规范时出现此错误:

Admins::BaseController
  before_filter#authenticate_admin!
    when admin is not logged in
      redirect admin to sign_in path (FAILED - 1)

Failures:

   1) Admins::BaseController before_filter#authenticate_admin! when admin is not logged     in redirect admin to sign_in path
     Failure/Error: get :index
     ActionView::MissingTemplate:
       Missing template anonymous/index, application/index with {:locale=>[:en],     :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}. Searched in:
         * "#<RSpec::Rails::ViewRendering::EmptyTemplatePathSetDecorator:0xbaf75d4>"
     # ./spec/controllers/admins/base_controller_spec.rb:17:in `block (4 levels) in <top (required)>'

Finished in 0.17124 seconds
1 example, 1 failure

Failed examples:

rspec ./spec/controllers/admins/base_controller_spec.rb:16 # Admins::BaseController   before_filter#authenticate_admin! when admin is not logged in redirect admin to sign_in path

我将我的规格更改为:

require 'spec_helper'

describe Admins::BaseController do
  controller do
    def index
      render nothing: true
    end
  end

  describe "before_filter#authenticate_admin!" do
    context "when admin is not logged in" do
      it "redirect admin to sign_in path" do
        get :index
        response.should redirect_to new_admin_session_path
      end
    end

  end
end

现在我收到了这个错误:

Failures:

  1) Admins::BaseController before_filter#authenticate_admin! when admin is not logged in redirect admin to sign_in path
     Failure/Error: response.should redirect_to new_admin_session_path
       Expected response to be a <:redirect>, but was <200>

所以,由于某种原因,它没有进入authenticate_admin!过滤前。我有点迷路了。再次感谢。

我正在使用 Rails 3.2.13、Ruby 2.0.0、Rspec-rails 2.13.0 和 Devise 2.2.3。如果有人可以帮助我解决这个问题,我真的很感激。提前致谢。

4

1 回答 1

4

好吧,3 小时后,我发现问题出在定义匿名控制器上。

代替:

controller do
  def index
  end
end

我用了:

controller(Admins::Base) do
  def index
  end
end

You need to specify always the anonymous controller you're testing unless is ApplicationController the one you're trying to test.

于 2013-03-20T18:19:04.943 回答