Skip to content

Instantly share code, notes, and snippets.

@losvedir
Last active December 25, 2015 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save losvedir/7051728 to your computer and use it in GitHub Desktop.
Save losvedir/7051728 to your computer and use it in GitHub Desktop.
Exploration into how Rspec could provide some of its nice syntactical features
require 'ostruct'
class Object
def expect(value)
@expector = Expector.new(value)
end
def eq(val)
[:==, val]
end
def method_missing(meth, *args)
match = /^be_(.*)/.match(meth)
if match
real_method = "#{match[1]}?".to_sym
[real_method]
else
super
end
end
class Expector < Struct.new(:expected_value)
def to(expectation_args)
results expected_value.send(*expectation_args)
end
def not_to(expectation_args)
results !expected_value.send(*expectation_args)
end
private
def results(bool)
puts (bool ? 'PASS!' : 'FAIL!')
end
end
end
happy_obj = OpenStruct.new(happy?: true, happiness: 5)
expect(happy_obj).to be_happy # => PASS!
expect(happy_obj).not_to be_happy # => FAIL!
expect(happy_obj.happiness).to eq 5 # => PASS!
expect(happy_obj.happiness).to eq 4 # => FAIL!
expect(happy_obj.happiness).not_to eq 4 # => PASS!
expect(happy_obj.happiness).not_to eq 5 # => FAIL!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment