【问题标题】:Getting tripped up by verify_partial_doubles with rails 4 and rspec 3使用 rails 4 和 rspec 3 被 verify_partial_doubles 绊倒
【发布时间】:2014-09-11 13:33:04
【问题描述】:

我正在使用 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 提供的保护,我该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails-4 mocking authlogic rspec3


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答。
    • 太棒了。这很有帮助。谢谢
    【解决方案2】:

    您可以按如下方式禁用视图的双重验证:

    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

    【讨论】:

    • 是的,谢谢。我只是觉得这太丑陋了,坦率地说,这代表了 rspec 的重大失败。整个“current_user 作为应用控制器中的辅助方法”设置很常见,不需要花费太多精力来完成这项工作。
    猜你喜欢
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多