Skip to content

Instantly share code, notes, and snippets.

@beccasaurus
Created February 4, 2011 22:38
Show Gist options
  • Save beccasaurus/811922 to your computer and use it in GitHub Desktop.
Save beccasaurus/811922 to your computer and use it in GitHub Desktop.
should_have_attributes
module ShouldHaveAttributes
class Validator
def initialize object
@object = object
end
def method_missing name, *args, &block
# puts "#{@object}.#{name}.should == #{args.first.inspect}"
@object.send(name).should == args.first
end
end
# Usage:
#
# user.should_have_attributes do
# name 'Bob'
# email '[email protected]
# end
#
# or:
#
# user.should_have_attributes do |u|
# u.name 'Bob'
# u.email '[email protected]
# end
#
# or:
#
# user.should_have_attributes :name => 'Bob', :email => '[email protected]'
#
def should_have_attributes attributes = nil, &block
unless attributes.nil?
attributes.each {|key, value| self.send(key).should == value }
end
Validator.new(self).indifferent_eval(&block) unless block.nil?
end
end
Object.send :include, ShouldHaveAttributes
# Without should_have_attributes
user = User.first
user.name.should == 'bob'
user.api_key.should == '123456'
user.api_url.should == 'http://foo.com'
# Using block
User.first.should_have_attributes do
name 'bob'
api_key '123456'
api_url 'http://foo.com'
end
# Passing attribute hash
User.first.should_have_attributes :name => 'bob', :api_key => '123456', :api_url => 'http://foo.com'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment