Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a method is called on an object - Rails RSpec

I have two models, Foo and Bar. Foo has a method called ask_bar_to_do_something, which is called after an instance of Foo is saved. This method does not change state of this Foo instance.

I am thinking of making this method to return 1, and create a lambda block that create Foo object and check the return value. Is there a better way to do this?

Thank you.

like image 590
AdamNYC Avatar asked Sep 19 '11 15:09

AdamNYC


1 Answers

Why not mock the object and expect the method call?

class Foo < ActiveRecord::Base
  after_create :ask_bar_to_do_something

  def ask_bar_to_do_something
    #blah blah blah
  end
end

If you are using factory to create the object

Foo.any_instance.should_receive(:ask_bar_to_do_something)
Factory(:foo)

Else

foo = Foo.new(:attr1 => 'value1', :attr2 => 'value2')
foo.should_receive(:ask_bar_to_do_something)
foo.save
like image 147
dexter Avatar answered Oct 22 '22 08:10

dexter