我在纯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 :(得分:4)
应该是:
expect(org.is_root?).to eq true
当您将阻止传递给expect
时,它会被ExpectationTarget
类包裹(严格来说BlockExpectationTarget < ExpectationTarget
)。由于您没有指定对此对象的期望,因此永远不会执行该块,因此不会引发错误。
答案 1 :(得分: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)