5

我正在使用 authlogic 进行用户身份验证,在我的 ApplicationController 中,我定义了“current_user”、“current_user_session”等并将其设置为 helper_methods。

我的主索引有一个非常简单的视图规范:

RSpec.describe "main/index.html.erb", :type => :view do
  context "when not logged in" do

    before do
      allow(view).to receive(:current_user).and_return(nil)
    end

    it "has an h1" do
      render
      expect(rendered).to include('h1')
    end

  end
end

问题是,如果我的配置中有“mocks.verify_partial_doubles = true”,那么这会导致一个令人印象深刻的巨大错误,因为它会转储整个对象,然后在底部说:

  1) main/index.html.erb when not logged in has an h1
     Failure/Error: allow(view).to receive(:current_user).and_return(nil)
       #<#<Class:0x00000104c249d0>:.........
       @rendered_views={}>> does not implement: current_user

当然,建议将 verify_partial_doubles 设置为 true,但这样做会中断。我直接从文档中提取了这个:

https://www.relishapp.com/rspec/rspec-rails/v/3-1/docs/view-specs/view-spec#passing-view-spec-that-stubs-a-helper-method

如果该方法出现在 ApplicationHelper 中,它将起作用。但如果它在 ApplicationController 中并定义为 helper_method 就没有这样的运气了:

helper_method :current_user, ...

def current_user
  return @current_user if defined?(@current_user)
  @current_user = current_user_session && current_user_session.record
end

我想要 verify_partial_doubles 提供的保护,我该如何解决这个问题?

4

2 回答 2

3

这是一个已知问题,使其工作的唯一方法是将方法提取到模块中并将其包含在您的视图助手和控制器中。

更多信息请访问:https ://github.com/rspec/rspec-rails/issues/1076

于 2014-09-19T12:55:47.120 回答
0

您可以禁用视图的双重验证,如下所示:

RSpec.configure do |config|
  config.before(:each, type: :view) do
    config.mock_with :rspec do |mocks|
      mocks.verify_partial_doubles = false
    end
  end

  config.after(:each, type: :view) do
    config.mock_with :rspec do |mocks|
      mocks.verify_partial_doubles = true
    end
  end
end

这样您就可以通过以下方式保持存根视图方法:

allow(view).to receive(:current_user).and_return(nil)

更多信息请访问:https ://github.com/rspec/rspec-rails/issues/1076

于 2016-07-29T20:29:15.623 回答