RSpec & Custom Matches with Multiple Arguments

I am trying to create custom matches for my tests in RoR using RSpec.

  define :be_accessible do |attributes|
    attributes = attributes.is_a?(Array) ? attributes : [attributes]
    attributes.each do |attribute|
      match do |response|
        response.class.accessible_attributes.include?(attribute)
      end
      description { "#{attribute} should be accessible" }
      failure_message_for_should { "#{attribute} should be accessible" }
      failure_message_for_should_not { "#{attribute} should not be accessible" }
    end
  end

In my tests, I want to write something like the following:

...
should be_accessible(:name, :surname, :description)
...

but with the above qualifier, I have to pass an array of characters instead of comma separated characters, otherwise the test only checks the first character.

Any ideas?

+5
source share
1 answer

I did it like this:

RSpec::Matchers.define :be_accessible do |*attributes|
  match do |response|

    description { "#{attributes.inspect} be accessible" }

    attributes.each do |attribute|
      failure_message_for_should { "#{attribute} should be accessible" }
      failure_message_for_should_not { "#{attribute} should not be accessible" }

      break false unless response.class.accessible_attributes.include?(attribute)
    end
  end
end

I inverted the loop matchand each. I think that’s exactly how Rspec expects the block given to the method matchto be executed by the abstract match of Rspec (I think).

|*attributes|, Array.

, should be_accessible(:name, :surname, :description) .

, ,

should respond_to(:name, :surname, :description)

. .

+4

All Articles