Within my test I want to stub a canned response for any instance of a class.
It might look like something like:
Book.stubs(:title).any_instance().returns("War and Peace")
Then whenever I call @book.title
it returns "War and Peace".
Is there a way to do this within MiniTest? If yes, can you give me an example code snippet?
Or do I need something like mocha?
MiniTest does support Mocks but Mocks are overkill for what I need.
If you're interesting in simple stubbing without a mocking library, then it's easy enough to do this in Ruby:
If you want something more complicated like stubbing all instances of a class, then it is also easy enough to do, you just have to get a little creative:
I use minitest for all my Gems testing, but do all my stubs with mocha, it might be possible to do all in minitest with Mocks(there is no stubs or anything else, but mocks are pretty powerful), but I find mocha does a great job, if it helps:
You can easily stub methods in
MiniTest
. The information is available at github.So, following your example, and using the
Minitest::Spec
style, this is how you should stub methods:This a really stupid example but at least gives you a clue on how to do what you want to do. I tried this using MiniTest v2.5.1 which is the bundled version that comes with Ruby 1.9 and it seems like in this version the #stub method was not yet supported, but then I tried with MiniTest v3.0 and it worked like a charm.
Good luck and congratulations on using MiniTest!
Edit: There is also another approach for this, and even though it seems a little bit hackish, it is still a solution to your problem:
You cannot do this with Minitest. However, you can stub any particular instance:
I thought I'd share an example that I built upon the answers here.
I needed to stub a method at the end of a long chain of methods. It all started with a new instance of a PayPal API wrapper. The call I needed to stub was essentially:
I created a class that returned itself unless the method was
amount
:Then I stubbed it in to
PayPal::API
:You could make this work for more than just one method by making a hash and returning
hash.key?(method) ? hash[method] : self
.