2014-04-09 21 views
2

我有一個這樣的類。如何使用rspec訪問即時變量

require 'net/http' 
class Foo 
    def initialize 
    @error_count = 0 
    end 
    def run 
    result = Net::HTTP.start("google.com") 
    @error_count = 0 if result 
    rescue 
    @error_count += 1 
    end 
end 

而且我想,如果連接失敗計數@error_count,所以我寫了這個樣子。

require_relative '富'

describe Foo do 
    before(:each){@foo = Foo.new} 

    describe "#run" do 
    context "when connection fails" do 
     before(:each){ Net::HTTP.stub(:start).and_raise } 
     it "should count up @error_count" do 
     expect{ @foo.run }.to change{ @foo.error_count }.from(0).to(1) 
     end 
    end 
    end 
end 

然後我得到這個錯誤。

NoMethodError: 
    undefined method `error_count' for #<Foo:0x007fc8e20dcbd8 @error_count=0 

如何使用Rspec訪問實例變量?

編輯

describe Foo do 
    let(:foo){ Foo.new} 
    describe "#run" do 
    context "when connection fails" do 
     before(:each){ Net::HTTP.stub(:start).and_raise } 
     it "should count up @error_count" do 
     expect{ foo.run }.to change{foo.send(:error_count)}.from(0).to(1) 
     end 
    end 
    end 
end 

回答

2

嘗試@foo.send(:error_count)我想它應該工作。

更新:found in docs

expect{ foo.run }.to change{foo.instance_variable_get(:@error_count)}.from(0).to(1) 
+0

此外,我建議使用'讓(:富){Foo.new}'根據http://betterspecs.org/,除非你是不是在[我們不要](http://robots.thoughtbot.com/lets-not)主題 – zishe

+0

我按照你的建議改變了spec文件,但是我仍然沒有'方法錯誤'。而且我不想讓這個屬性可以從另一個類訪問。有什麼我可以嘗試嗎? – ironsand

+0

我更新了答案 – zishe