-
-
Save RobertAudi/35aa662b8413d1ed49ad57f09e517286 to your computer and use it in GitHub Desktop.
Custom Rspec matcher for checking class for constant, with optional class type.
This file contains hidden or 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
# frozen_string_literal: true | |
class ExampleClass | |
PI = 3.14159265359 | |
end |
This file contains hidden or 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
# frozen_string_literal: true | |
require 'spec_helper' | |
RSpec.describe ExampleClass do | |
it { expect(described_class).to have_constant(:PI, Float) } | |
it { expect(described_class).to define_constant(:PI, Float) } | |
end |
This file contains hidden or 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
# frozen_string_literal: true | |
# | |
# File: spec/support/matchers/have_constant.rb | |
RSpec::Matchers.define :have_constant do |const, klass| | |
match do |owner| | |
if klass.nil? | |
owner.const_defined?(const) | |
else | |
owner.const_defined?(const) && owner.const_get(const).class == klass | |
end | |
end | |
failure_message do |actual| | |
msg = +"constant #{expected[0]} not defined in #{actual}" | |
msg += " as a #{expected[1]}" unless expected[1].nil? | |
msg | |
end | |
failure_message_when_negated do |actual| | |
msg = +"constant #{expected[0]} is defined in #{actual}" | |
msg += " as a #{expected[1]}" unless expected[1].nil? | |
msg | |
end | |
description do | |
msg = +"have constant #{const}" | |
msg += " defined with class #{klass}" unless klass.nil? | |
msg | |
end | |
end | |
RSpec::Matchers.alias_matcher :define_constant, :have_constant |
This file contains hidden or 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
# frozen_string_literal: true | |
# | |
# File: spec/spec_helper.rb | |
Dir[File.join(__dir__, "/support/**/*.rb")].each { |f| require f } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment