1

我有这些用于测试控制器身份验证的 shared_examples_for 方法。

支持/控制器/authentication_helpers.rb

module ControllerHelpers
  include Devise::TestHelpers

  shared_examples_for 'authenticate user' do |user, method, action, url_params={}|
    before(:each) do 
      setup_controller_for_warden
      request.env["devise.mapping"] = Devise.mappings[:user]
    end
    it "should redirect visitors to login page" do
      sign_out user
      if method == :get
        get action, url_params
      elsif method == :post
        post action, url_params
      elsif method == :put
        put action, url_params
      elsif method == :delete
        delete action, url_params
      end
      response.should redirect_to new_user_session_path
    end
    it "should allow user" do
      sign_in user
      if method == :get
        get action, url_params
      elsif method == :post
        post action, url_params
      elsif method == :put
        put action, url_params
      elsif method == :delete
        delete action, url_params
      end
      response.should be_success
    end
  end

end

我想将它与我的控制器规范文件一起使用。

Brief_controller_spec.rb

require 'spec_helper'

describe BriefController do
  render_views

  before(:all) do
    @customer=Factory(:customer)
    @project=Factory(:project_started, :owner => @customer)
  end

  context 'get :new' do
    it_behaves_like 'authenticate user', @customer, :get, :new, {:project_id => @project.to_param} 
  end
end

当我运行这些规范文件时,我遇到了错误

Failure/Error: sign_in user
     RuntimeError:
       Could not find a valid mapping for

你知道我该如何处理这个错误吗?

4

3 回答 3

0

我认为问题在于在代码执行it_behaves_like之前要评估的参数,因此第一个参数 ( ) 的计算结果为,从而导致进一步的问题。我用自己的代码浪费了很多时间来解决这个问题。before@usernil

在相关的一点上,我最近阅读了一个建议,以避免在此类测试中使用实例变量,因为您希望在未定义它们时对它们的引用失败。这对我来说很有意义,这就是我现在所做的。

于 2013-07-02T21:16:39.710 回答
0

我使用 let 块作为实例变量解决了我的问题。

shared_examples_for 'authenticate user' do |method, action|
    before(:each) do 
      setup_controller_for_warden
      request.env["devise.mapping"] = Devise.mappings[:user]
    end
    it "should redirect visitors to login page" do
      if method == :get
        get action, url_params
      elsif method == :post
        post action, url_params
      elsif method == :put
        put action, url_params
      elsif method == :delete
        delete action, url_params
      end
      response.should redirect_to new_user_session_path
    end

控制器规格.rb

context 'get :new' do
    it_behaves_like 'authenticate user', :get, :new do 
      let(:user) { @customer }
      let(:url_params) { { :project_id => @project.to_param } }
    end
  end
于 2013-07-03T11:23:43.857 回答
0

我在这里可能是错的,但我认为:

@customer=Factory(:customer)
@project=Factory(:project_started, :owner => @customer)

应该:

@customer=FactoryGirl(:customer)
@project=FactoryGirl(:project_started, :owner => @customer)

简单的错误,我自己犯了几次。试试看能不能解决问题,希望对你有帮助。

于 2013-07-02T16:36:11.677 回答