Tag Archives: rspec

belong_to RSpec matcher

I was extending acts_as_commentable and needed a good RSpec test to check the returned objects from its finder methods belonged to the correct user. For example, Comment.find_comments_by_user( :some_user ) should all belong_to :some_user. I’ll be darned if that doesn’t look like a RSpec description. Since there is no all_belong_to matcher, I wrote one.

module ActiveRecordValidations
  class BelongTo
    def initialize(expected)
      @expected = expected
    end
 
    def matches?(args)
      args.all? do |target|
        @target = target
        @target.send(@expected.class.to_s.downcase) == @expected
      end
    end
 
    def failure_message
      "expected #{@target.inspect} to all belong to #{@expected}"
    end
 
    def negative_failure_message
      "expected #{@target.inspect} not to all belong to #{@expected}"
    end
  end
 
  def belong_to(expected)
    BelongTo.new( [expected] )
  end
 
  def all_belong_to(expected)
    BelongTo.new( expected )
  end
end

The matches? method takes an array of objects and goes through them with all? checking that they have a belongs_to the expected thing. Using the example above, each comment object returned by Comment.find_comments_by_user would get tested if comment.user== @user.

–Dean