Created
June 30, 2021 13:21
-
-
Save hopsoft/eace7bd8b95c5b527d3f6a4df49239de to your computer and use it in GitHub Desktop.
Asserts with equality check and detailed expected/got failure messages
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
module ThreadAwareEquality | |
refine BasicObject do | |
alias_method :original_equals, :== | |
def ==(other) | |
Thread.current[:actual] = self | |
Thread.current[:expected] = other | |
original_equals other | |
end | |
end | |
end | |
# ------------------------------------------------------------------------------ | |
module ThreadAwareAssertions | |
def assert(value, msg = nil) | |
clean_thread do | |
expect(Thread.current[:actual]).to eql(Thread.current[:expected]) | |
end | |
end | |
def refute(value, msg = nil) | |
clean_thread do | |
expect(Thread.current[:actual]).not_to eql(Thread.current[:expected]) | |
end | |
end | |
private | |
def clean_thread | |
yield | |
ensure | |
Thread.current.keys.delete :actual | |
Thread.current.keys.delete :expected | |
end | |
end | |
# ------------------------------------------------------------------------------ | |
using ThreadAwareEquality | |
# first describe block uses Minitest::Assertions which are lazily meta defined, | |
# and they are nearly impossible to override with a mixin 🤷♂️ | |
describe "example" do | |
# nested describe blocks will actually honor the mixed in assertions | |
describe "assert" do | |
include ThreadAwareAssertions | |
# fails but prints the expected rspec expected/got comparison message | |
# | |
# expected: true | |
# got: false | |
# | |
it "works as expected" do | |
assert false == true | |
end | |
end | |
describe "refute" do # nested blocks will actually honor the mixed in assertions | |
include ThreadAwareAssertions | |
# fails but prints the expected rspec expected/got comparison message | |
# | |
# expected: value != true | |
# got: true | |
# | |
it "works as expected" do | |
refute true == true | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment