您将如何在 Ruby on Rails 应用程序中使用 rSpec 测试观察者?
-
09-06-2019 - |
题
假设您的 Ruby on Rails 应用程序之一中有一个 ActiveRecord::Observer - 如何使用 rSpec 测试该观察者?
解决方案
您的方向是正确的,但在使用 rSpec、观察者和模拟对象时,我遇到了许多令人沮丧的意外消息错误。当我对模型进行规范测试时,我不想在消息期望中处理观察者行为。
在您的示例中,如果不知道观察者将对其执行什么操作,则没有一种真正好的方法可以在模型上指定“set_status”。
因此,我喜欢使用 “禁止偷窥狂”插件。 鉴于您上面的代码并使用 No Peeping Toms 插件,我将像这样指定模型:
describe Person do
it "should set status correctly" do
@p = Person.new(:status => "foo")
@p.set_status("bar")
@p.save
@p.status.should eql("bar")
end
end
您可以规范您的模型代码,而不必担心有一个观察者会进来并破坏您的值。您可以在 person_observer_spec 中单独指定它,如下所示:
describe PersonObserver do
it "should clobber the status field" do
@p = mock_model(Person, :status => "foo")
@obs = PersonObserver.instance
@p.should_receive(:set_status).with("aha!")
@obs.after_save
end
end
如果您真的想测试耦合的模型和观察者类,您可以这样做:
describe Person do
it "should register a status change with the person observer turned on" do
Person.with_observers(:person_observer) do
lambda { @p = Person.new; @p.save }.should change(@p, :status).to("aha!)
end
end
end
99% 的情况下,我宁愿在关闭观察器的情况下进行规范测试。这样就更容易了。
其他提示
免责声明:我实际上从未在生产站点上这样做过,但看起来合理的方法是使用模拟对象, should_receive
和朋友,并直接调用观察者上的方法
给定以下模型和观察者:
class Person < ActiveRecord::Base
def set_status( new_status )
# do whatever
end
end
class PersonObserver < ActiveRecord::Observer
def after_save(person)
person.set_status("aha!")
end
end
我会写一个这样的规范(我运行了它,它通过了)
describe PersonObserver do
before :each do
@person = stub_model(Person)
@observer = PersonObserver.instance
end
it "should invoke after_save on the observed object" do
@person.should_receive(:set_status).with("aha!")
@observer.after_save(@person)
end
end
no_peeping_toms 现在是一个 gem,可以在这里找到: https://github.com/patmaddox/no-peeping-toms
如果您想测试观察者是否观察到正确的模型并按预期接收通知,这里有一个使用 RR 的示例。
你的模型.rb:
class YourModel < ActiveRecord::Base
...
end
your_model_observer.rb:
class YourModelObserver < ActiveRecord::Observer
def after_create
...
end
def custom_notification
...
end
end
your_model_observer_spec.rb:
before do
@observer = YourModelObserver.instance
@model = YourModel.new
end
it "acts on the after_create notification"
mock(@observer).after_create(@model)
@model.save!
end
it "acts on the custom notification"
mock(@observer).custom_notification(@model)
@model.send(:notify, :custom_notification)
end
不隶属于 StackOverflow