thoughtbot/shoulda-context

A way to reuse should blocks

Closed this issue · 1 comments

I find myself writing a lot of different contexts and repeating the same should block.
Is there a way to avoid this repetition?

The reason is that one method has different conditions for a if block to execute and so alternatively I'm setting up different attributes in the context and using the same should block.

Maybe I'm supposed to assign the specific attributes right inside the should block?

Sorry for the delay on this. It probably would have been better to submit this as a StackOverflow question, but you have at least two options.

  1. You can write your own customer matchers. You can see examples in shoudla-matchers
  2. You can encapsulate your should block into it's own method (sometimes called a macro). I use these when I don't want the complexity of building a full matcher.

Here's a quick example of a "macro." They can contain one or many should blocks.

  def self.should_set_private_cache_headers
    should "set private cache headers" do
      assert_match /private/, response.headers["Cache-Control"]
      assert_nil response.headers["Last-Modified"]
    end
  end

If you'd like the macro to also take a block, you can bind the block to the inner should block with merge_block:

merge_block(&block)