How to get instance_of to work with ActiveRecord objects in RoR?

Today I ran into an issue using RoR to stub calls to AR objects. I thought that I'd be able to do something along the lines of :

stub.instance_of(BankAccount).save_to_other_spot { true }

However when I tried this method it didn't seem to stub the method at all and it would end up running the original method I was trying to stub. I confirmed this using debugger etc.

So I ended up using the following method :

stub.proxy(BankAccount).find(anything) do |account|
  stub(account).save_to_other_spot { true }

This works.

I was wondering if I'm doing something wrong though? Why doesn't instance_of work in the way I expect?

Another issue I ran into was that in my RSpec tests I seem to have to setup my mocks and stubs for each request. Again, is this normal or am I doing something wrong?

By this I mean I'd have to do something like :

... mock and stub ...
get :show, :id => @id

... mock and stub ...
post :update, :id => id, :account => { ... params ... }

I thought I'd be able to mock and stub once at the top.


Assuming you are running RSpec >2.5... then the mock/stubbing syntax has been improved so that you can now use the following definition.

BankAccount.any_instance.stub(:save_to_other_spot) { true }

Note you will need to use a latter version of RSpec. The earlier versions of RSpec do not include the any_instance method. It looks like they borrowed this from Mocha and implemented it into RSpec mocks.

If you are using the older versions of RSpec, then what you're doing I think is the only way. Only that I tend to write it like this:

@bank_account =
BankAccount.stub(:find) { @bank_account }
@bank_account.stub(:save_to_other_spot) { true }

Albeit I think your block method looks cleaner.

Need Your Help

Why can't C++ have an optional transparent garbage collector

c++ garbage-collection

There's a related question but this one is slightly different and I'm not happy with any of the answers to the related question :)

Excel VBA - count the duplicates

vba excel-vba

I have two arrays which contains string values in them. Let us consider the example as below.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.