2016-02-20 16 views
1

我試圖從電子書中運行一些示例RSpec示例,但它看起來該書的舊版本爲RSpec,因此一些示例引用了舊的RSpec API,這是造成問題的原因。我試圖儘可能解決他們,但因爲我是Ruby & RSpec對我來說有點挑戰性。無法訪問RSpec測試中的變量

從錯誤日誌中我可以看出這是一個範圍問題,但不知道如何解決它。

subject仍然是rspec 3.4.2版本的一部分嗎?

$rspec --version 
3.4.2 

不起作用

require "spec_helper" 
describe Location do 
    describe "#initialize" do 
     subject { Location.new(:latitude => 38.911268, :longitude => -77.444243) } 
     expect(:latitude).to eq(38.911268) 
     expect(:longitude).to eq(-77.444243) 
    end 
end 

錯誤日誌:

method_missingexpect不可上的示例基團(例如一個或describecontext塊)。它只能在各個示例(例如it塊)內或來自在示例範圍內運行的構造(例如before,let等)提供。 (RSpec :: Core :: ExampleGroup :: WrongScopeError)

+2

錯誤消息告訴你到底發生了什麼問題:你在示例以外使用'except'。它必須在'it'塊中。附:他們仍然無法工作。符號':latitude'僅等於':latitude'(就像字符串''latitude'''只等於''latitude''')。它永遠不會等於一個數字。也許你的意思是'subject.latitude'? –

回答

1

正如上面的評論所述,您在使用此規範時遇到了一些問題。你可以重構爲以下幾點:

describe Location do 
    describe "#initialize" do 
    subject { Location.new(latitude: 38.911268, longitude: -77.444243) } 

    it "longitude & latitude is set" do 
     expect(subject.latitude).to eq (38.911268) 
     expect(subject.longitude).to eq (-77.444243) 
    end 
    end 
end 

以下幾點上是怎麼回事:


RSpec explicit subject

  • 文檔說:利用主題組範圍明確定義在示例範圍中由主題方法返回的值爲 。
  • 你同樣可以有它使用let這樣定義:

  • let(:location) { Location.new(latitude: 38.911268, longitude: -77.444243) }

  • 你將被使用location而不是subject在您的測試對象。

Describe vs it blocks

  • 文檔說:該描述方法創建的示例組。在傳遞給 的塊中,描述您可以使用describe或context 方法聲明嵌套組,或者可以使用它或指定方法聲明示例。
  • 您可以繼續並添加context塊。

    describe "something" do 
        context "in one context" do 
        it "does one thing" do 
         ###expect something 
        end 
        end 
    
        context "in another context" do 
        it "does another thing" do 
         ###expect something else 
        end 
        end 
    end 
    

基本上任何代碼,expects(即你的規範的期望)總是要到it塊內坐。