cgore.comcgore@cgore.commicroblogblogphotosChristianitycryptographyjournalingoutdoorsmy master's thesisprogramming
Thinking Bicycle
Github @cgoreFacebook @cgoreInstagram @christopher.mark.gore

This website is copyright © 1995-2016 Christopher Mark Gore, all rights reserved. The content may not be copied or republished via any means, traditional or electronic, without express written permission of the author.

Chris Gore: Programming: Ruby: RSpec Change Blocks

I use RSpec a lot for testing when I am in Ruby, and one nice feature that I just figured out is that the change term can take a block as the argument. The normal form is something like this:

expect { @something.add(12) }
.to change(@something, :value).from(0).to(12)

But, if you need to pass arguments to the method that will indicate the change that has occurred, then you will need to pass a block to change. Here is an example:

@repo =
expect { @repo.add_package @xcalc }
.to change { @repo.existing_package? @xcalc }

This can be really nice in general, because you can put lots of stuff in a block. Most tests should really boil down to this format anyway:

expect { some_action }.to change { something }.from(old).to(new)