Take the 2-minute tour ×

I have a way to set should_receive expectations on a mock object, but it strikes me as a bit odd.

def mock_fax_event(stubs={})
  @mock_fax_event ||= mock_model(FaxEvent, stubs)

it "should notify facility/admin of failed faxes" do
  FaxEvent.should_receive(:find_by_fax_id).with(@fax_event.fax_id).and_return(mock_fax_event(:notify_failure => true))
  post :create, :TransactionID => @fax_event.fax_id

To me, I would like to do something like the following, but it doesn't work:

it "should notify facility/admin of failed faxes" do
  post :create, :TransactionID => @fax_event.fax_id

I think I understand why the above doesn't work, but I think the way I'm doing it now is unclear. I would also like to only test if notify_failure is actually called, not the find_by_fax_id part.

Is there a better way to do what I'm trying to do?

share|improve this question
add comment

1 Answer

Your second example doesn't work because it's a chicken-and-egg kind of problem. You're setting an expectation on an object after the post call which is what causes that object to become assigned in the first place. And you can't just swap the lines because assigns doesn't have anything to return yet.

If you don't care about whether or not find_by_fax_id gets called, the best you can do is call FaxEvent.stub(:find_by_fax_id).and_return(...), but that's not much better.

This is one of the reasons I like using Mocha. You can do this:

post :create, :TransactionID => @fax_event.fax_id

It lets you skip the annoying "find my mock object instead of what you'd actually find" step.

Also, :TransactionID goes against naming conventions, it should be :transaction_id.

share|improve this answer
Thanks, I will check out Mocha; I am becoming overwhelmed by testing frameworks. As far as the TransactionID, it's posted into the controller via an external service that I can not control, so not much I can do about it :) Will wait around to see if anyone else has something to say before awarding the answer, thanks for your comment. –  Preston Marshall Apr 22 '11 at 6:52
add comment

Your Answer


