technicalpickles

Open Source ProjectsCode that Might be Useful to You

Talks I've GivenOn Technologies and Ideas

ThoughtsWhere I Sometimes Write Things

Resume If You Still Believe In Those

Follow Me On

GitHubIf coding is your thing

TwitterIf you tweet

Shoulda can automatically load custom macros


I wrote about creating your own shoulda macros awhile back. At that point, I was suggesting to place these in your test/test_helper.rb.

Now it’s even easier, thanks to a semi recent change.

You can now create put .rb files in test/shoulda_macros, and Shoulda will automatically pick them up. Let’s try making a will_paginate macro, and stick it out in test/shoulda_macros/will_paginate_macros.rb:

module WillPaginateMacros
  def should_have_per_page(count)
    klass = self.name.gsub(/Test$/, '').constantize
    context "#{klass}" do
      should "respond to per_page" do
        assert klass.respond_to?(:per_page), "#{klass} does not respond to :per_page"
      end
      
      should "have #{count} per page" do
        assert_equal count, klass.per_page
      end
    end
  end
end

class Test::Unit::TestCase
  extend WillPaginateMacros
end

In the test of an imaginary Post model, which I’m sure you can picture, we can do:

require File.dirname(__FILE__) + '/../test_helper'

class UserTest < ActiveSupport::TestCase
  # ...
  should_have_per_page 10
end

BOOYAH!

For plugin and gem authors, vendor/gems/*/shoulda_macros/*.rb and vendor/plugins/*.rb will also be automatically picked up.

comments powered by Disqus