2014-09-11 28 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