Skip to content

Instantly share code, notes, and snippets.

@rokumatsumoto
Forked from RobertAudi/example.rb
Last active April 14, 2022 19:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rokumatsumoto/d5a76b1031738a5cde2d8dedbfc454a5 to your computer and use it in GitHub Desktop.
Save rokumatsumoto/d5a76b1031738a5cde2d8dedbfc454a5 to your computer and use it in GitHub Desktop.
Custom RSpec matcher for checking class for constant, with optional class type and value
# frozen_string_literal: true
class ExampleClass
POPULAR_LIMIT = 12
end
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe ExampleClass do
subject { described_class }
it { is_expected.to have_constant(:POPULAR_LIMIT, Integer).with_value(12) }
it { is_expected.to define_constant(:POPULAR_LIMIT, Integer).with_value(12) }
end
# frozen_string_literal: true
#
# File: spec/support/matchers/have_constant.rb
RSpec::Matchers.define :have_constant do |const, klass|
match do |owner|
return owner.const_defined?(const) if klass.nil?
return owner.const_defined?(const) && owner.const_get(const).class == klass if @value.nil?
owner.const_defined?(const) && owner.const_get(const).class == klass &&
owner.const_get(const) == @value
end
chain :with_value do |value|
@value = value
end
failure_message do |actual|
msg = +"constant #{const} not defined in #{actual}"
msg += " as a #{klass}" unless klass.nil?
msg += " with value #{@value}" unless @value.nil?
msg
end
failure_message_when_negated do |actual|
msg = +"constant #{const} is defined in #{actual}"
msg += " as a #{klass}" unless klass.nil?
msg += " with value #{@value}" unless @value.nil?
msg
end
description do
msg = +"have constant #{const}"
msg += " defined with class #{klass}" unless klass.nil?
msg += " and value #{@value}" unless @value.nil?
msg
end
end
RSpec::Matchers.alias_matcher :define_constant, :have_constant
# 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