Last active
December 25, 2015 22:39
-
-
Save losvedir/7051728 to your computer and use it in GitHub Desktop.
Exploration into how Rspec could provide some of its nice syntactical features
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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