Created
August 27, 2013 17:32
-
-
Save redconfetti/6356551 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
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
require 'spec_helper' | |
describe ExampleClass do | |
its(:class) { should have_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
# 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 |
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
# 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