开发者

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 }
  account
end

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.new
BankAccount.stub(:find) { @bank_account }
@bank_account.stub(:save_to_other_spot) { true }

Albeit I think your block method looks cleaner.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜