开发者

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

开发者 https://www.devze.com 2023-04-06 02:31 出处:网络
I have two开发者_C百科 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 have two开发者_C百科 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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消