Stub an AR Model Instance Method

Obviously, I’m missing something very simple, can someone please
explain how to stub an instance of an AR model method.

This does not work:
@widget = Widget.first # Widget has an instance method called
‘next_seriel_number’
@widget.stub(:next_serial_number).and_return(43, nil)

I know I could use ‘any_instance’, and that does work, expect that I
need to return multiple values. And ‘any_instance’ does not work with
returning multiple values.

This does not work:
Widget.any_instance.stub(:next_serial_number).and_return(43, nil) #
only returns 43

On Thu, Jun 9, 2011 at 14:33, Karl [email protected] wrote:

returning multiple values.

This does not work:
Widget.any_instance.stub(:next_serial_number).and_return(43, nil) #
only returns 43

Google “rspec mock_model” and off you go. Good luck.

J. B. (Joe) Rainsberger :: http://www.jbrains.ca ::
http://blog.thecodewhisperer.com
Diaspar Software Services :: http://www.diasparsoftware.com
Author, JUnit Recipes
2005 Gordon Pask Award for contribution to Agile practice :: Agile
2010: Learn. Practice. Explore.

On Jun 9, 2011, at 12:33 PM, Karl wrote:

Obviously, I’m missing something very simple, can someone please
explain how to stub an instance of an AR model method.

This does not work:
@widget = Widget.first # Widget has an instance method called
‘next_seriel_number’
@widget.stub(:next_serial_number).and_return(43, nil)

“This does not work:” doesn’t tell us what the problem is. Please be
specific. Are you getting a failure? If so, please show us the complete
code for the example, including any before hooks, and the failure
message you’re getting.

Found my problem… mostly due to my misunderstanding of mocks. Joe’s
suggestion above led me down the right path. This worked:

@account = mock_model(Account)
@account.stub!(:next_serial_number).and_return(43, nil)
Widget.any_instance.stub(:account).and_return(@account)

On Sat, Jun 18, 2011 at 21:10, Karl [email protected] wrote:

Found my problem… mostly due to my misunderstanding of mocks. Joe’s
suggestion above led me down the right path. This worked:

@account = mock_model(Account)
@account.stub!(:next_serial_number).and_return(43, nil)
Widget.any_instance.stub(:account).and_return(@account)

I’m glad you found something that did what you wanted. Now what are
you trying to do with it? I’ve never wanted to stub
:next_serial_number before, so I’d like to understand the situation
you find yourself in, for when that happens to me.

J. B. (Joe) Rainsberger :: http://www.jbrains.ca ::
http://blog.thecodewhisperer.com
Diaspar Software Services :: http://www.diasparsoftware.com
Author, JUnit Recipes
2005 Gordon Pask Award for contribution to Agile practice :: Agile
2010: Learn. Practice. Explore.