2013-04-14 66 views
35
class TestController < AplicationController 
    #.... 

    private 

    def some_method 
    unless @my_variable.nil? 
     #... 
     return true 
    end 
    end 
end 

我想測試some_method直接在控制器規格:Rspec的:如何實例變量賦值在控制器規範

require 'spec_helper' 

describe TestController do 
    it "test some_method" 
    phone = Phone.new(...) 
    controller.assign(:my_variable,phone) #does not work 
    controller.send(:some_method).should be_true 
    end 
end 

如何設置TestController實例變量@my_variable從控制器規範?

回答

53

當在控制器中測試私有方法而不是使用send時,我傾向於使用anonymous controller,這是因爲不想直接調用私有方法,而是私有方法的接口(或者在下面的測試中,有效地存儲該接口) 。所以,你的情況,也許是這樣的:

require 'spec_helper' 

describe TestController do 
    controller do 
    def test_some_method 
     some_method 
    end 
    end 

    describe "a phone test with some_method" do 

    subject { controller.test_some_method } 

    context "when my_variable is not nil" do 
     before { controller.instance_variable_set(:@my_variable, Phone.new(...)) } 
     it { should be_true } 
    end 

    context "when my_variable is nil" do 
     before { controller.instance_variable_set(:@my_variable, nil) } 
     it { should_not be_true } # or should be_false or whatever 
    end  
    end 
end 

有關於在this StackOverflow Q&A直接測試私有方法,它動搖了我對使用匿名控制器的問題提出一些很好的討論,但你的意見可能會有所不同。

+1

謝謝@保羅有一個好的解決方案。 – ole

2

我不認爲你想從規範控制器訪問一個實例變量,因爲spec應該測試行爲,但是你總是可以存儲私有方法。 你的情況應該是這樣的(在這個例子中它沒有那麼多的意義):

describe TestController do 
    it "test some_method" 
    phone = Phone.new(...) 
    controller.stub(:some_method).and_return(true) 
    controller.send(:some_method).should be_true 
    end 
end 

如果這是你正在尋找沒有什麼看看這個:How to set private instance variable used within a method test?

0

instance_eval是實現這種相對清潔的方式:

describe TestController do 
    it "test some_method" do 
    phone = Phone.new(...) 
    controller.instance_eval do 
     @my_variable = phone 
    end 
    controller.send(:some_method).should be_true 
    end 
end 

在這種情況下,使用do...endinstance_eval是矯枉過正,而這些三線可以縮短爲:

controller.instance_eval {@my_variable = phone} 
相關問題