2014-05-20 66 views
1

我有一個純Ruby模型一個RSpec測試:純Ruby的RSpec測試通過,就沒有辦法被定義

require 'spec_helper' 
require 'organization' 

describe Organization do 
    context '#is_root?' do 
    it "creates a root organization" do 
     org = Organization.new 

     expect { org.is_root?.to eq true } 
    end 
end 
end 

我的組織模式是這樣的:

class Organization 
    attr_accessor :parent 

    def initialize(parent = nil) 
    self.parent = parent 
end 
end 

運行測試時,輸出:

bundle exec rspec spec/organization_spec.rb:6 
Run options: include {:locations=>{"./spec/organization_spec.rb"=>[6]}} 
. 

Finished in 0.00051 seconds 
1 example, 0 failures 

當我運行測試,它通過,儘管方法is_root?在模型上不存在。我通常在Rails中工作,而不是純Ruby,而且我從未見過這種情況。到底是怎麼回事?

謝謝!

+0

您可以張貼輸出運行在終端測試 – cvibha

+0

你也可以啓動一個'軌console',問'後o.methods.select做| M | m.match/root/end'來驗證你對'is_root?'的假設嗎?' – Patru

+0

顯然它的測試在期望{}中。當我放入org.method(:is_root?)時,我得到一個失敗:'1)Organization#is_root?創建根組織 失敗/錯誤:org.method(:is_root?) NameError: 未定義的方法'is_root?' '組織' #./spec/organization_spec.rb:10:in'方法' #./spec/organization_spec.rb:10:in '' – rainslg

回答

2

您正在傳遞一個塊,期望從​​未被調用。您可以通過該塊

expect { org.is_root?.to eq true }.to_not raise_error 

    1) Organization#is_root? creates a root organization 
    Failure/Error: expect { puts "HI";org.is_root?.to eq true }.to_not raise_error 
     expected no Exception, got #<NoMethodError: undefined method `is_root?' for #<Organization:0x007ffa798c2ed8 @parent=nil>> with backtrace: 
     # ./test_spec.rb:15:in `block (4 levels) in <top (required)>' 
     # ./test_spec.rb:15:in `block (3 levels) in <top (required)>' 
    # ./test_spec.rb:15:in `block (3 levels) in <top (required)>' 

或者通過只把一個普通的加薪或放塊,這兩者都不將被稱爲內上設置一個期望看到這一點:

expect { puts "HI"; raise; org.is_root?.to eq true } 

塊形式使用期待一段代碼引發異常。檢查值正確的語法是:

expect(org.is_root?).to eq(true) 
4

它應該是:

expect(org.is_root?).to eq true 

當你傳遞塊expect它被包裹在ExpectationTarget類(嚴格地說BlockExpectationTarget < ExpectationTarget)。既然你沒有指定你對這個對象的期望,那麼這個塊永遠不會被執行,因此不會引發錯誤。

相關問題