您将如何在 Ruby on Rails 应用程序中使用 rSpec 测试观察者?
假设您的 Ruby on Rails 应用程序之一中有一个 ActiveRecord::Observer - 如何使用 rSpec 测试该观察者?
Suppose you have an ActiveRecord::Observer in one of your Ruby on Rails applications - how do you test this observer with rSpec?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
免责声明:我实际上从未在生产站点上这样做过,但看起来合理的方法是使用模拟对象、should_receive 和朋友,并直接在观察者上调用方法
给定以下模型和观察者:
我会写一个这样的规范(我运行了它,它通过了)
Disclaimer: I've never actually done this on a production site, but it looks like a reasonable way would be to use mock objects,
should_receive
and friends, and invoke methods on the observer directlyGiven the following model and observer:
I would write a spec like this (I ran it, and it passes)
您的方向是正确的,但在使用 rSpec、观察者和模拟对象时,我遇到了许多令人沮丧的意外消息错误。 当我对模型进行规范测试时,我不想在消息期望中处理观察者行为。
在您的示例中,如果不知道观察者将对其执行什么操作,则没有一种真正好的方法可以在模型上指定“set_status”。
因此,我喜欢使用 “No Peeping Toms”插件。 鉴于您上面的代码并使用 No Peeping Toms 插件,我会像这样指定模型:
您可以指定您的模型代码,而不必担心有一个观察者会进来并破坏您的模型价值。 您可以在 person_observer_spec 中单独指定,如下所示:
如果您真的真的想测试耦合的 Model 和 Observer 类,您可以这样做:
99% 的时间,我宁愿在关闭观察者的情况下进行规范测试。 这样就更容易了。
You are on the right track, but I have run into a number of frustrating unexpected message errors when using rSpec, observers, and mock objects. When I am spec testing my model, I don't want to have to handle observer behavior in my message expectations.
In your example, there isn't a really good way to spec "set_status" on the model without knowledge of what the observer is going to do to it.
Therefore, I like to use the "No Peeping Toms" plugin. Given your code above and using the No Peeping Toms plugin, I would spec the model like this:
You can spec your model code without having to worry that there is an observer out there that is going to come in and clobber your value. You'd spec that separately in the person_observer_spec like this:
If you REALLY REALLY want to test the coupled Model and Observer class, you can do it like this:
99% of the time, I'd rather spec test with the observers turned off. It's just easier that way.
no_peeping_toms 现在是一个 gem,可以在这里找到: https://github.com/patmaddox/no-偷窥狂
no_peeping_toms is now a gem and can be found here: https://github.com/patmaddox/no-peeping-toms
如果您想测试观察者是否观察到正确的模型并按预期接收通知,这里有一个使用 RR 的示例。
your_model.rb:
your_model_observer.rb:
your_model_observer_spec.rb:
If you want to test that the observer observes the correct model and receives the notification as expected, here is an example using RR.
your_model.rb:
your_model_observer.rb:
your_model_observer_spec.rb: