2014-05-20 62 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)。既然你没有指定你对这个对象的期望,那么这个块永远不会被执行,因此不会引发错误。

相关问题