通过用rails 4和rspec 3的verify_partial_doubles绊倒

Mic*_*ney 5 mocking authlogic ruby-on-rails-4 rspec3

我正在使用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
Run Code Online (Sandbox Code Playgroud)

问题是,如果在我的配置中“ 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
Run Code Online (Sandbox Code Playgroud)

当然,建议将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
Run Code Online (Sandbox Code Playgroud)

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

小智 3

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

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