Testing within an ActiveRecord block

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.