Skip to content

Instantly share code, notes, and snippets.

@gaizka
Created September 24, 2010 15:29
Show Gist options
  • Save gaizka/595545 to your computer and use it in GitHub Desktop.
Save gaizka/595545 to your computer and use it in GitHub Desktop.
module MyRspecCustomMatcher
class CheckAttributes
attr_accessor :object, :expected_val, :actual_val, :attribute
def initialize(expected)
@expected = expected
end
def matches?(actual)
self.object = actual
# actual is object
@expected.all? do |key, val|
self.actual_val = object.send(key)
self.expected_val = val
self.attribute = key
actual_val == expected_val
end
end
def failure_message_for_should
"object of class #{object.class} should have '#{expected_val}' as #{attribute}, but has '#{actual_val}'"
end
end
def have_these_attributes(expected)
CheckAttributes.new(expected)
end
end
$ rake
-- create_table(:users)
-> 0.0359s
-- create_table(:apples)
-> 0.0006s
-- initialize_schema_migrations_table()
-> 0.0010s
-- assume_migrated_upto_version(1, "db/migrate")
-> 0.0003s
User
- should be useful as a test of spec custom matchers
- should be cleaner this way
- example as a failing spec (FAILED - 1)
1)
'User example as a failing spec' FAILED
object of class User should have '363' as age, but has '367'
./user_spec.rb:31:
Finished in 0.036559 seconds
3 examples, 1 failure
ask :default do
system("spec --color -f specdoc user_spec.rb")
end
require 'rubygems'
require 'active_record'
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Schema.define(:version => 1) do
create_table :users do |t|
t.string :login
t.string :full_name
t.date :date_of_birth
end
create_table :apples do |t|
t.references :user
t.string :color
end
end
class User < ActiveRecord::Base
has_many :apples
before_create :set_login
def age
now = Time.now.utc.to_date
now.year - date_of_birth.year - ((now.month > date_of_birth.month || (now.month == date_of_birth.month && now.day >= date_of_birth.day)) ? 0 : 1)
end
private
def set_login
self.login = full_name.downcase.gsub(/ /, "_")
end
end
require 'user'
require 'my_rspec_custom_matcher'
Spec::Runner.configure do |config|
config.include(MyRspecCustomMatcher)
end
describe User do
before do
u = User.create(:login => @login, :full_name => "Isaac Newton", :date_of_birth => "1643-01-04")
end
it "should be useful as a test of spec custom matchers" do
user = User.find_by_full_name("Isaac Newton")
user.login.should == "isaac_newton"
user.age.should == 367
end
it "should be cleaner this way" do
user = User.find_by_full_name("Isaac Newton")
user.should have_these_attributes ({
:login => "isaac_newton",
:age => 367 })
end
it "example as a failing spec" do
user = User.find_by_full_name("Isaac Newton")
user.should have_these_attributes({
:login => "isaac_newton",
:age => 363 })
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment