belong_to RSpec matcher

by Dean

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.

  1. module ActiveRecordValidations
  2.   class BelongTo
  3.     def initialize(expected)
  4.       @expected = expected
  5.     end
  6.  
  7.     def matches?(args)
  8.       args.all? do |target|
  9.         @target = target
  10.         @target.send(@expected.class.to_s.downcase) == @expected
  11.       end
  12.     end
  13.  
  14.     def failure_message
  15.       "expected #{@target.inspect} to all belong to #{@expected}"
  16.     end
  17.  
  18.     def negative_failure_message
  19.       "expected #{@target.inspect} not to all belong to #{@expected}"
  20.     end
  21.   end
  22.  
  23.   def belong_to(expected)
  24.     BelongTo.new( [expected] )
  25.   end
  26.  
  27.   def all_belong_to(expected)
  28.     BelongTo.new( expected )
  29.   end
  30. 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

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Posted by: Dean @ 4:59 pm

Categories: Dean, code, ruby |

Leave a Reply

You must be logged in to post a comment.

Our Sponsors