Skip to content

Instantly share code, notes, and snippets.

@gittmaan
Created November 7, 2012 23:41
Show Gist options
  • Save gittmaan/4035409 to your computer and use it in GitHub Desktop.
Save gittmaan/4035409 to your computer and use it in GitHub Desktop.
Minitest rspec or spec matchers and shared behaviours
# 100.should be_multiple_of(10)
#rspec
Rspec::Matchers.define :be_multiple_of do |multiple|
match do |number|
number % multiple == 0
end
failure_message_for_should do |number|
"Expected #{number} to be multiple of #{multiple}"
end
end
# minitest
# assert_multiple_of 10, 100
module MiniTest::Assertions
def assert_multiple_of(multiple, number, msg = nil)
message = msg || "Expected #{number} to be multiple of #{multiple}"
assert_equal 0, number % multiple, message
end
end
# minitest::spec
# 100.must_be_multiple_of 10
class Object
def must_be_multiple_of(expected)
assert_multiple_of expected, self
end
end
#or
Object.infect_an_assertion :assert_multiple_of, :must_be_multiple_of
#or
Numeric.infect_an_assertion :assert_multiple_of, :must_be_multiple_of
# minitest -> spec mapping
infect_an_assertion :assert_equal, :must_equal
infect_an_assertion :assert_match, :must_match
infect_an_assertion :assert_empty, :must_be_empty, :unary # tell not have actual<->expected swap only one argument like array.must_be_empty(no argument here )
# convention
# minitest
assert_equal expected, actual
# spec
actual.must_equal expected
#so
[].must_be_empty(no arg to flip)
assert_empty []
Object.infect_an_assertion :assert_empty, :must_be_empty
class Object
def must_be_empty
assert_empty , self # error
end
end
# converts to
Object.infect_an_assertion :assert_empty, :must_be_empty, :unary
class Object
def must_be_empty
assert_empty self # happy :)
end
end
###
# shared behavior
###
module SharedBehavior
end
class MyTestClass1
include SharedBehavior
end
class MyTestClass2
include SharedBehavior
end
# rspec way
shared_examples 'as implemented in shared behavior module' do
it 'is as implemented in shared behavior module' do
do_somthing = somthing_to_do
do_somthing.should include(SharedBehavior)
end
end
describe 'First example' do
include_examples 'as implemented in shared behavior module'
end
describe 'Next example' do
include_examples 'as implemented in shared behavior module'
end
# minitest way
describe 'First example' do
include AsImplementedInShared
end
describe 'Next example' do
include AsImplementedInShared
end
module AsImplementedInShared
def self.included(spec_class)
spec_class.class_eval do
it 'as implemented in shared behavior' do
do_somthing = self.class.desc
do_somthing.must_include(SharedBehavior)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment