Jul 09 loading custom rspec matchers into cucumber

tags: rspec cucumber matchers | comments

I happen to need to make expectations about a created user on a complex step, so when the chunk started to repeat I make myself an RSpec matcher to do that, and then load it into cucumber to be able to use it in my steps.

I was wanting to be able do to some like this:

Given "I have signed up as (.+) who is an (.+)" do |user, role| do
    # call some steps to create user tom
    # my expectation is to guarantee that user tom really have the required rol
    user.should have_role(role)
end

The RSpec matchers syntax has really make awesome progresses since the first ones I wrote a year back (you needed to create a class with some methods, not very rubylicious), now take a look to this new way:

Spec::Matchers.define :have_role do |role|
   match do |user|
      user.roles.collect{ |r| r.name }.include?(role)
   end
end

Then the easy way as suggested by Ben Mabey in the rspec list and is to throw the matcher declaration (that last chunk of code) into your env.rb.

I organized it a little more taking the webrat way, first you namescope your matcher:

module MyCustom
  module Matchers
    Spec::Matchers.define :have_rol do |role|
      match do |user|
        user.roles.collect{ |r| r.name }.include?(role)
      end
    end
  end
end

you create a spec/support/my_custom_matchers.rb and there you load your custom matchers:

Spec::Runner.configure do |config|
  # rspec should support :type => [:controller, :helper, :view] - but until it does ...
  config.include(MyCustom::Matchers, :type => :controller)
  config.include(MyCustom::Matchers, :type => :helper)
  config.include(MyCustom::Matchers, :type => :view)
end

then you only need to require your custom matchers in your env.rb:

require File.expand_path(File.dirname(__FILE__) + "../../../spec/support/my_custom_matchers")

if your matchers start to become many, you could put them in spec/support/matchers/ and then in spec/support/my_custom_matchers.rb you iterate the matchers directory requiring and loading all of them.

blog comments powered by Disqus