2012-12-27 50 views
0

我想我明白隱式主題如何在RSpec中工作,但我不知道。RSpec'指定'通過明確的主題,但不與隱式主題

爲什麼,在以下的例子中,使用顯式主體通過第一規範,但使用隱式主題的第二規格失敗,「未定義的方法`匹配爲#」:

class Example 
    def matches(str) ; true ; end 
end 

describe Example do 
    subject { Example.new } 
    specify { subject.matches('bar').should be_true } 
    it { matches('bar').should be_true } 
end 

(我使用rspec 1.3,但我用2.10.1驗證了相同的行爲。)

回答

2

回到一些基本的ruby:你基本上調用self.matches,在這種情況下self是一個RSpec示例。

可以調用之類的東西「應該」在這個例子中,使用的參數,所以你可以嘗試這樣的:

it { should matches('bar') } 

但這會失敗;自己還沒有方法matches

但是,在這種情況下,主題確實是matches方法,而不是示例實例。所以,如果你想繼續使用隱含的主題,你的測試可能是這樣的:

class Example 
    def matches(str) ; str == "bar" ; end 
end 

describe Example do 
    describe "#matches" do 
    let(:method) { Example.new.method(:matches) } 

    context "when passed a valid value" do 
     subject { method.call("bar") } 
     it { should be_true } 
    end 

    context "when passed an invalid value" do 
     subject { method.call("foo") } 
     it { should be_false } 
    end 
    end 
end 
+0

尼斯。您將主題塊中的「匹配」調用(並將其用於不同示例的參數化)的澄清將其清除!謝謝! –

0

我不認爲你可以調用隱式主題的任何方法。隱含的主題含義你不需要指定主題,但如果你想調用任何方法,你需要指定主題。