2014-09-11 79 views
4

我使用authlogic进行用户身份验证,并在我的ApplicationController中定义了“current_user”,“current_user_session”等,并将其设置为helper_methods。通过verify_partial_doubles with rails 4和rspec 3获取绊倒

我有一个非常简单的视图规格为我的主要指标:

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 =真”在我的配置那么这会导致大量的令人印象深刻的错误,因为它转储整个对象,然后说在底部:

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提供保护,我怎么能解决此问题?

回答

3

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

的更多信息:https://github.com/rspec/rspec-rails/issues/1076

+0

Thanks for th答案。 – 2014-09-19 20:18:49

+0

辉煌。这非常有帮助。谢谢 – GhostRider 2015-05-19 16:08:01

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

+0

是的,谢谢你。我只是觉得这不是丑陋的,坦率地说,这是RSpec的一次重大失败。整个“current_user作为应用程序控制器中的辅助方法”设置已经足够普遍,所以它不应该花费很多精力来完成这项工作。 – 2016-08-01 16:53:53