Good notes posted by Olly

RSS feed
August 15, 2008
7 thanks

anything matcher

The anything matcher will match any ruby object:

  1.should == anything
  nil.should == anything
  'string'.should == anything

  var.should_receive(:method).with(param1, anything)
August 14, 2008
11 thanks

Testing an options hash receives certain parameters

This method is very useful for testing methods that use the ruby idiom of accepting a hash with configurable options.

  class Example
    def self.find(options = {})
      ...
    end
  end

We can use hash_including to ensure that certain options are passed in when mocking it.

  Example.should_receive(:find).with(hash_including(:conditions => 'some conditions'))

  Example.find(:conditions => 'some_conditions', :order => 1)
  # => Passes expectation

  Example.find(:order => 1)
  # => Fails expectation

This can also be used to great effect with the anything matcher. For example:

  hash_including(:key => anything)

  hash_including(anything => 'value')
August 14, 2008
4 thanks

Convert an Array of Arrays to a Hash using inject

Converting an array of arrays to a hash using inject:

  array = [['A', 'a'], ['B', 'b'], ['C', 'c']]

  hash = array.inject({}) do |memo, values|
    memo[values.first] = values.last
    memo
  end

  hash
  # => {'A' => 'a', 'B' => 'b', 'C' => 'c'}
August 8, 2008
10 thanks

Using validates_format_of to validate URIs

You can use the validates_format_of with the regular expression in the URI library ensure valid URIs.

Example

  require 'uri'

  class Feed < ActiveRecord::Base
    validates_format_of :uri, :with => URI.regexp
  end