Skip to content

Instantly share code, notes, and snippets.

@RobertAudi
Forked from redconfetti/example.rb
Last active March 23, 2020 14:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save RobertAudi/35aa662b8413d1ed49ad57f09e517286 to your computer and use it in GitHub Desktop.
Save RobertAudi/35aa662b8413d1ed49ad57f09e517286 to your computer and use it in GitHub Desktop.
Custom Rspec matcher for checking class for constant, with optional class type.
# frozen_string_literal: true
class ExampleClass
PI = 3.14159265359
end
# 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
# 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
# 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