thoughtbot / shoulda-context

Shoulda Context makes it easy to write understandable and maintainable tests under Minitest and Test::Unit within Rails projects or plain Ruby projects.
MIT License
239 stars 58 forks source link

A way to reuse should blocks #30

Closed afast closed 10 years ago

afast commented 11 years ago

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?

rmm5t commented 10 years ago

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)