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.
If you ever get down to this level, don’t you feel like your tests will exactly mimic your implementation?
July 20, 2012 at 6:44 am
Granted it’s a trivial example, you may be doing something more exciting inside a block that you feel requires testing.
July 20, 2012 at 7:13 am