Skip to content

Instantly share code, notes, and snippets.

@rfkdali
Created November 15, 2018 18:38
Show Gist options
  • Save rfkdali/4dd195bdeac1ba6aa158d9b6bde4d5fc to your computer and use it in GitHub Desktop.
Save rfkdali/4dd195bdeac1ba6aa158d9b6bde4d5fc to your computer and use it in GitHub Desktop.
Implementing Rspec DSL
require 'test/unit'
class AssertionError < StandardError; end
class Matcher
attr_accessor :matcher_value, :matcher_type
def initialize(matcher_value, matcher_type)
@matcher_value = matcher_value
@matcher_type = matcher_type
end
end
class Expectation
def initialize(arg)
@arg = arg
end
def to(arg)
case arg.matcher_type
when 'greater_than' then raise(AssertionError.new) unless @arg > arg.matcher_value
when 'eq' then raise(AssertionError.new) unless @arg == arg.matcher_value
when 'raise_error'
if @arg.is_a? Proc
begin
raise AssertionError.new if @arg.call.is_a? Integer
rescue => e
raise unless e.is_a? RuntimeError
end
else
raise AssertionError.new('You should use a Proc')
end
end
end
def not_to(arg)
raise(AssertionError.new) if @arg == arg.matcher_value
end
end
class RspecTest < Test::Unit::TestCase
def test_eq_succeeds
assert_nothing_raised { expect(6).to eq(6) }
end
def test_eq_raises_when_not_equal
assert_raise(AssertionError) { expect(6).to eq(4) }
end
def test_not_eq_succeeds
assert_nothing_raised { expect(6).not_to eq(4) }
end
def test_not_eq_raises_when_equal
assert_raise(AssertionError) { expect(6).not_to eq(6) }
end
def test_be_greater_than_succeeds
assert_nothing_raised { expect(6).to be_greater_than(4) }
end
def test_be_greater_than_raises_when_not_greater_than
assert_raise(AssertionError) { expect(6).to be_greater_than(6) }
end
def test_raise_error_succeeds
assert_nothing_raised { expect(lambda { raise 'oops' }).to raise_error }
end
def test_raise_error_raises_when_nothing_raised
assert_raise(AssertionError) { expect(lambda { 2 + 2 }).to raise_error }
end
private
def expect(arg)
Expectation.new(arg)
end
def eq(value)
Matcher.new(value, 'eq')
end
def be_greater_than(value)
Matcher.new(value, 'greater_than')
end
def raise_error
Matcher.new(nil, 'raise_error')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment