2016-06-21 61 views
0

所以我對Rails非常陌生,並且在RSpec中掙扎了一番,特別是嘲笑某些事情。所以我有一個模塊(關注),我的一些控制器正在使用。該模塊(ValidateAdmin)在current_user和logged_in_user中調用另外兩個函數。爲了覆蓋最多的可能性,我想將這兩個函數存根並設置它們的返回值。有關如何完成這項工作的任何建議?控制器的RSpec嘲諷模塊功能

describe ValidateAdmin do 
    before :all do 
    class FakeController < ApplicationController 
     include ValidateAdmin 
    end 
    end 

let(:controller) { FakeController.new } 

describe '#validate_admin_logged_in' do 
    controller.stub(:current_user).and_return(instance_double(User, admin?: true)) 
    controller.stub(:logged_in_user).and_return(instance_double(User, admin?: true)) 
    [RSpec contexts go here] 

編輯 - 修正它包含我之前的'塊'的模擬語句。也只是實現存根被棄用,所以切換到允許語句。

+0

現在使用你當前的代碼會發生什麼? –

+0

@MohammadAbuShady對不起,沒有把這個問題,我有點匆忙。它拋出了一個非常奇怪的錯誤,儘管我通過將它包含在'before'塊中來解決它。愚蠢的錯誤在我的部分,但感謝您的迴應。 – jdune

回答

0

控制器實例可以像任何其他對象一樣被樁起來。您可能還需要添加路由:

describe FakeController, type: :controller do 
    let(:admin_user) { instance_double(User, admin?: true) } 

    it "performs my excellent test" do 
    allow(controller).to receive(:current_user).and_return(admin_user) 
    routes.draw { get "custom_action" => "fake#custom_action" } 
    get :custom_action 
    end 
end 

let(:controller)是uneccessary - RSpec的這是否爲您服務。此外,測試類不需要進入before塊 - 它可以簡單地定義在文件的頂部,或者需要-d。

+0

我的問題是我在哪裏有我的存根語句 - 修正了我通過將它放在'before'塊中而得到的奇怪錯誤。也從存根更改爲允許,因爲我發現已棄用。謝謝! – jdune