So you forgot to add a uniqueness constraint to a table in your db and over time, race conditions have wreaked havoc on your validates_uniqueness_of validations.

Time to clean out those duplicates!

module DuplicateFinder
 
  def find_duplicate_sets_on_keys *uniqueness_keys
    uniqueness_list = uniqueness_keys.join(', ')
    find(:all, :select => "#{uniqueness_list}, COUNT(#{primay_key}) AS total", :group => "#{uniqueness_list} HAVING total > 1")
  end
 
  def find_duplicates_for_set duplicate_set, options = {}
    uniqueness_keys = duplicate_set.attributes.reject do |attr_name, attr_value| attr_name == 'total' end.keys
    condition_values = uniqueness_keys.map do |uniqueness_key| duplicate_set.send uniqueness_key end
    uniqueness_condition = [ uniqueness_keys.map do |uniqueness_key| "#{uniqueness_key} = ?" end.join(' AND ') ] + condition_values
 
    with_scope :find => { :conditions => uniqueness_condition } do
      find(:all, options)
    end
  end
 
end
 
class ActiveRecord::Base
 
  class << self
    include DuplicateFinder
  end
 
end

Now you find and operate on duplicates within your migration like so:

require 'duplicate_finder'
 
class AddIndexForFavoriteColor < ActiveRecord::Migration
  class FavoriteColor < ActiveRecord::Base
    def self.destroy_duplicates!
      find_duplicate_sets_on_keys(:user_id, :color_id).each do |duplicate_set|
        dups = find_duplicates_for_set(duplicate_set)
 
        # All but the last
        dups[0..-2].each do |duplicate|
          duplicate.destroy
        end
 
      end
    end
  end
 
  def self.up
    FavoriteColor.destroy_duplicates!
    add_index :favorite_colors, [:user_id, :color_id], :unique => true
  end
 
  def self.down
    remove_index :favorite_colors, :column => [:user_id, :color_id]
  end
end

I split the find_duplicate_sets_on_keys and find_duplicates_for_set up to minimize the number of records instantiated at any given time.

Last month, Thoughtbot’s Matt Jankowski wrote up a post about How to not accidentally send thousands of ‘beta invites’.

The method outlined is elegant and simple. It also requires modifying the recipients of all of your ActionMailer models.

We wanted something that would allow our QA team to safely test email-sending features all over the site, and without a lot of management overhead.

module ActionMailer
  class Part
    def to_mail_with_capture defaults
      self.body += defaults.captures
      to_mail_without_capture defaults
    end
    alias_method_chain :to_mail, :capture
  end
 
  class Base
 
    cattr_writer :captured_email_recipient_address
 
    def captured_email_recipient_address
      @@captured_email_recipient_address
    end
 
    def captures
      # Add information about captured recipients to the footer of the email body
      captured_addresses = @captures.map do |method, addresses|
 
        if addresses.kind_of?(Array)
          captured_address = [
            "<ul>",
            addresses.map { |a| "<li>#{a}</li>" },
            "</ul>"
          ].join
        else
          captured_address = addresses
        end
 
        [
          "<dl>",
            "<dt>", method, "</dt>",
            "<dd>", captured_address, "</dd>",
          "</dl>"
        ].join
      end
 
      captured_addresses_report = [
        "<div><p>Intended recipients</p>",
        captured_addresses,
        "</div>"
      ].join
 
      captured_addresses_report
    end
 
    def captured method, list
      @captures ||= {}
      @captures[method] = list
      self.recipients_without_capture = captured_email_recipient_address
    end
 
    def recipients_with_capture= list
      captured :recipients, list
    end
    def cc_with_capture= list
      captured :cc, list
    end
    def bcc_with_capture= list
      captured :bcc, list
    end
 
    # Defer to the overridden setters if setting the list of recipients
    # Otherwise, return the unaliased list
    def recipients_with_capture list = nil
      list ? self.recipients_with_capture= list : recipients_without_capture
    end
    def cc_with_capture list = nil
      list ? self.cc_with_capture= list : cc_without_capture
    end
    def bcc_with_capture list = nil
      list ? self.bcc_with_capture= list : bcc_without_capture
    end
 
    alias_method_chain :cc=, :capture
    alias_method_chain :bcc=, :capture
    alias_method_chain :recipients=, :capture
    alias_method_chain :cc, :capture
    alias_method_chain :bcc, :capture
    alias_method_chain :recipients, :capture
 
  end
end

Requiring this file will cause all ActionMailer deliveries to be sent to one address, which you can set by using:

ActionMailer::Base.captured_email_recipient_address = "testing@yourdomain.com"

Additionally, a div will be appended to the email body indicating who its intended recipients were, and how the email would have been sent to them; recipient, cc, or bcc. Perfect for QA!

We simply set up the testing address as a mailing list in Google Docs, so we don’t have to manage who gets these emails from within the application, and can instead use Google’s tools.

Remember to set in your deploy recipe whether or not emails should be captured, as you wouldn’t want to accidentally capture all the email being sent out from your live application!

UPDATE: A more comprehensive method of comparing arrays is covered in this updated article.

When you don’t care what order items in an array are in, don’t pretend you do.

Say you’ve got a list of expected results, and some rows returned by the database:

expected_words = [ 'some', 'known', 'items' ]
found_words = Words.find( :all, :conditions => [ 'name IN (?)', expected_words ] ).map { |w| w.name }

Instead of asserting:

assert_equal expected_words, found_words

Consider:

assert_same_elements expected_words, found_words

To achieve this, I follow the pattern presented by Jay Fields in Convention Is Important, extending a core object and placing the extension in central location. In my case, this location is lib/core_extensions/array/same_elements.rb

class Array
  # Ask an Array whether it shares the same elements with another Array, irrespective of order
  # Options
  # :allow_duplicates
  #   If set to true arrays with the same elements, but differing numbers of those elements
  #   are treated as the same.
  #   Examples
  #     [ :a ].same_elements?( [ :a, :a ] ) => false
  #     [ :a ].same_elements?( [ :a, :a ], :allow_duplicates => true) => true
  def same_elements? another_array, options = {}
    raise ArgumentError, "#{another_array.inspect} was expected to be an Array" unless another_array.kind_of?(Array)
    s = self
    a = another_array
    if options[:allow_duplicates]
      s = s.uniq
      a = a.uniq
    end
 
    return element_counts(s) == element_counts(a)
  end
 
  private
    def element_counts obj
      result = []
      obj.uniq.map { |e|
        [ e, obj.inject(0) { |i, e2| i + (e == e2 ? 1 : 0 ) } ]
      }.each { |p| result << p.first; result << p.last }
      Hash[ *result ]
    end
end

This extensions allows us to ask an array about its similarity to another array.

The most interesting part of this method is the element_counts, which returns a hash whose keys are the unique elements of the array and whose values are the number of instances of each unique value in the original array.

In order to be able to use this in your tests, simply add this small helper method to test/test_helper.rb

# Assert two enumerables have the same elements, irrespective of order
def assert_same_elements enum1, enum2, *args
  message = args.last.kind_of?(String) ? args.pop : "Expected Arrays to have same elements"
  options = args.last.kind_of?(Hash) ? args.pop : {}
  assert_block(build_message(message, "<?> expected to have the same elements as \n<?>.\n", enum2, enum1)) { enum1.same_elements?(enum2, options) }
end

Bonus: Tests

require File.dirname(__FILE__) + '/../unit_test_helper'
 
class ArraySameElementsTest < Test::Unit::TestCase
  def test_same_elements_with_identical_arrays
    assert_equal true, [ :a ].same_elements?( [ :a ] )
  end
 
  def test_same_elements_with_no_shared_items
    assert_equal false, [ :a ].same_elements?( [ :b ] )
  end
 
  def test_same_elements_with_different_ordering
    assert_equal true, [ :a, :b ].same_elements?( [ :b, :a ] )
  end
 
  def test_same_elements_should_not_allow_duplicates
    assert_equal false, [ :a ].same_elements?( [ :a, :a ] ), 'Should not allow duplicates in other array.'
    assert_equal false, [ :a, :a ].same_elements?( [ :a ] ), 'Should not allow duplicates in self.'
    assert_equal false, [ :a, :b, :b ].same_elements?( [ :a, :a, :b ] ), 'Should not allow different duplicates in self and other.'
    assert_equal true, [ :a, :b, :b ].same_elements?( [ :a, :b, :b ] ), 'Should allow duplicates present in both self and other.'
  end
 
  def test_same_elements_should_allow_duplicates_if_allow_duplicates
    assert_equal true, [ :a ].same_elements?( [ :a, :a ], :allow_duplicates => true )
    assert_equal true, [ :a, :a ].same_elements?( [ :a ], :allow_duplicates => true )
    assert_equal true, [ :a, :b, :b ].same_elements?( [ :a, :a, :b ], :allow_duplicates => true )
  end
 
  def test_same_elements_should_not_allow_different_elements_if_allow_duplicates
    assert_equal false, [ :a, :b ].same_elements?( [ :a, :a, :b, :c ], :allow_duplicates => true )
  end
 
  def test_same_elements_should_raise_argument_error_if_provided_argument_is_not_an_array
    assert_raise_with_error_message ArgumentError, :error_message => / was expected to be an Array$/ do
      [ ].same_elements? nil
    end
  end
end

Sometimes I want to verify the value within a constant is handled in a certain way, independently of what the actual value in the constant is defined as.

So I change it, temporarily.

ApplicationConfig.override_constant(:RECORD_ANALYTICS, false) do
  puts "For the duration of this block, RECORD_ANALYTICS is #{ApplicationConfig::RECORD_ANALYTICS}"
end

# Override the value of a Module Constant for the duration of a block.
class Module
  def override_constant constant_name, new_value
    raise ArgumentError, 'No block provided to establish a context in which the constant is overridden' unless block_given?
    # Cannot override unless constant is defined in Module
    raise NameError, "#{self} does not define #{constant_name}" unless const_defined?(constant_name)
 
    # Store original value to replace it at the end
    original_value = const_get(constant_name)
 
    # Remove original definition
    remove_const constant_name
 
    # Insert alternative definition
    const_set constant_name, new_value
 
    begin
      yield
 
    ensure
      # Remove alternative definition
      remove_const constant_name
 
      # Restore original definition
      const_set constant_name, original_value
    end
  end
end

class OverrideConstantTest < Test::Unit::TestCase
  module TestModule
    DEFINED_CONSTANT = true
  end
 
  def test_should_raise_argument_error_when_block_is_not_provided
    assert_raise_with_error_message ArgumentError, :error_message => 'No block provided to establish a context in which the constant is overridden' do
      TestModule.override_constant :DEFINED_CONSTANT, true
    end
  end
 
  def test_should_raise_error_when_module_does_not_define_constant
    assert_raise_with_error_message NameError, :error_message => 'OverrideConstantTest::TestModule does not define NO_SUCH_CONSTANT' do
      TestModule.override_constant :NO_SUCH_CONSTANT, true do
      end
    end
  end
 
  def test_should_alter_value_of_constant_for_duration_of_block
    assert_equal true, TestModule::DEFINED_CONSTANT
 
    TestModule.override_constant :DEFINED_CONSTANT, false do
      assert_equal false, TestModule::DEFINED_CONSTANT
    end
 
    assert_equal true, TestModule::DEFINED_CONSTANT
  end
 
end

Verifying errors are raised is handy, but are you sure you’re capturing the right one?

Check the message!

# assert_raise allows you to check for the type of an error but not to check the error messages contents
# This is a wrapper to assert_raise that adds this functionality.
#
# Use with the traditional assert_raise syntax
# http://www.ruby-doc.org/stdlib/libdoc/test/unit/rdoc/classes/Test/Unit/Assertions.html
#
# To specify the error message, provide a string or regular expression to the :error_message option
#
# Example
# assert_raise_with_error_message ArgumentError, :error_message => /is not refuelable$/ do
#   outfitter.refuel(Asteriod.new)
# end
#
class Test::Unit::TestCase
  def assert_raise_with_error_message *args, &block
    options = args.last.kind_of?(Hash) ? args.pop : {}
    exception = assert_raise *args, &block
    expected_message = options[:error_message]
    case expected_message
    when String
      assert_equal expected_message, exception.message
    when Regexp
      assert_match expected_message, exception.message
    end
  end
end