Testing within an ActiveRecord block

July 19, 2012 Robbie Clutton

Following on from the article about ActiveRecord blocks and a similar topics at the office book club, I’ve been trying to put some of these concepts into my code. I did find it difficult to figure out how to test within the block. Below I’ll outline what we did to test the code within the block.

Say we’ve got a Foo class which inherits from ActiveRecord.

class Foo < ActiveRecord::Base end 

When create a new foo, we can use a block to mutate the object.

Foo.create(args) do |foo| foo.x = 1 end 

In the test, we want to return a stub, but we can’t assert that x was called on that stub as the block won’t be executed.

Foo.should_receive(:create) { foo_stub } foo_stub.should_receive(:x=) # assertion fails 

We can use a block after the ‘should_receive’ call to get the block as a Proc and call it with the stub we want to run assertions on.

Foo.should_receive(:create) do |args, &block| block.call(foo_stub) end 

Now we can successfully test inside the block.

About the Author

Robbie Clutton

Robbie Clutton is the Head of Pivotal Labs in EMEA.

Previous
Cloud Foundry and Open PaaS at OSCON
Cloud Foundry and Open PaaS at OSCON

The Cloud Foundry team is at the premier Open Source conference, O’Reilly OSCON this week. What a differenc...

Next
Jasmine Testing: Param(s) passed to a method.
Jasmine Testing: Param(s) passed to a method.

Recently, I've been using a nice way to test if the correct arguments have been passed to a method. This us...

×

Subscribe to our Newsletter

!
Thank you!
Error - something went wrong!