"how would you test observers with rspec in a ruby on rails application?" Code Answer


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:

describe person do 
  it "should set status correctly" do 
    @p = person.new(:status => "foo")
    @p.status.should eql("bar")

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

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!)

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

By rlecaro2 on July 5 2022
Only authorized users can answer the Search term. Please sign in first, or register a free account.