Skip to content

Instantly share code, notes, and snippets.

@redconfetti
Created August 27, 2013 17:32
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 redconfetti/6356551 to your computer and use it in GitHub Desktop.
Save redconfetti/6356551 to your computer and use it in GitHub Desktop.
Custom Rspec matcher for checking class for constant, with optional class type.
class ExampleClass
PI = 3.14159265359
end
require 'spec_helper'
describe ExampleClass do
its(:class) { should have_constant(:PI, Float) }
end
# spec/support/matchers/have_constant.rb
RSpec::Matchers.define :have_constant do |const,klass|
match do |owner|
const_defined = owner.const_defined?(const)
klass_match = owner.const_get(const).class == klass unless klass.nil?
klass.nil? ? const_defined : (const_defined && klass_match)
end
failure_message_for_should do |actual|
msg = "constant #{expected[0]} not defined in #{actual}"
msg += " as a #{expected[1]}" unless expected[1].nil?
msg
end
failure_message_for_should_not 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
# spec/spec_helper.rb
Dir[File.dirname(__FILE__) + "/support/**/*.rb"].each {|f| require f}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment