我现在正在学习一些Ruby,我决定从在线教程(http://www.sitepoint.com/design-patterns-in-ruby-observer-singleton/)中重新教授一些设计模式。所以我有两个类文件:
汽车
require_relative 'Notifier'
require 'observer'
class Car
include Observable
attr_reader :mileage, :service
def initialize(mileage = 0, service = 3000)
@mileage, @service = mileage, service
add_observer(Notifier.new)
end
def log(miles)
@mileage += miles
changed
notify_observers(self, miles)
end
end
通知者:
class Notifier
def update(car, miles)
puts "The car has logged #{miles} miles, totalling #{car.mileage} miles traveled."
puts "The car needs to be taken in for a service!" if car.service <= car.mileage
end
端
这是我的测试:
require_relative 'car'
require "test/unit"
class CarTest <
Test::Unit::TestCase
def test_simple
assert_equal("The car has logged 100 miles, totaling 2400 miles traveled.", Car.new(2300, 3000).log(100))
end
end
但每当我运行测试时,我都会收到此失败消息,想知道是否有人知道为什么会发生这种情况?
[1/1] CarTest#test_simpleThe car has logged 100 miles, totalling 2400 miles traveled.
= 0.00 s
1) Failure:
test_simple(CarTest) [car_test.rb:8]:
<"The car has logged 100 miles, totaling 2400 miles traveled."> expected but was
<false>.
答案 0 :(得分:3)
puts
打印到stdout。但是您的测试需要Car#log
的返回值。这就是它失败的原因。
在同一个说明中,为什么要在Notifier
的测试中测试Car
的内部结构?
更好的方法是确保观察者得到正确的信息而不关心它的副作用(当然,对于观察者有一个专门的规范,这将测试副作用和诸如此类的东西)
def test_simple
# sorry, RSpec lingo here, I'm not a minitest guy
expect_any_instance_of(::Notifier).to receive(:update).with(car, 2400)
Car.new(2300, 3000).log(100)
end