在一个Ruby on Rails应用程序,你会如何测试与RSpec的观察员?观察员、你会、应用程序、测试

由网友(酒酿樱桃子)分享简介:假设你有一个ActiveRecord ::观察员在你的Ruby on Rails应用程序之一 - 你怎么使用RSpec测试这个观察者Suppose you have an ActiveRecord::Observer in one of your Ruby on Rails applications - how do...

假设你有一个ActiveRecord ::观察员在你的Ruby on Rails应用程序之一 - 你怎么使用RSpec测试这个观察者

Suppose you have an ActiveRecord::Observer in one of your Ruby on Rails applications - how do you test this observer with rSpec?

推荐答案

你是在正确的轨道上,但我已经用RSPEC,观察员和模仿对象时遇到了一些令人沮丧的意外消息错误。当我规范测试我的模型,我不希望有来处理我的消息的预期观察者的行为。

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.

在你的榜样,没有符合规范set_status不上什么样的观察者会做它的知识模型,一个非常好的办法。

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.

所以,我喜欢用不偷窥插件。鉴于你code以上,并使用无偷窥插件,我会SPEC这样的模式:

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:

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

您可以规范模型code,而不必担心有观察员在那里,是要进来,揍你的价值。你会单独规格,在这样的person_observer_spec:

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:

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 

如果你真的真的要测试的耦合模型和观察员类,你可以做到这一点是这样的:

If you REALLY REALLY want to test the coupled Model and Observer class, you can do it like this:

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%的时间,我宁愿规范的测试与观察关闭。这只是更容易这样。

99% of the time, I'd rather spec test with the observers turned off. It's just easier that way.

阅读全文

相关推荐

最新文章