Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stratigos/159d1797d2fdd2f12091097ad4fb2d51 to your computer and use it in GitHub Desktop.
Save stratigos/159d1797d2fdd2f12091097ad4fb2d51 to your computer and use it in GitHub Desktop.
RSpec Boolean Matcher Shared Example with Shoulda Matchers
# Shared specs for models with the `:validates_inclusion_of` validators, where
# Boolean values are specified. This is for use cases where Booleans are used
# in non-null DB columns, and validation errors need to be returned to actors
# attempting to store a NULL value (e.g., a IoT unit's firmware uploading a
# NULL value for an On/Off sensor reading).
# Additionally, `shoulda` will complain if `validate_inclusion_of` is used
# with the Booleans, and instead of turning off warnings, its best to just
# approach these specs differently. See
# [this github comment](https://github.com/thoughtbot/shoulda-matchers/issues/922#issuecomment-225752673)
# for more info.
RSpec.shared_examples :validates_boolean_model do |attribute_name, options|
it { is_expected.to allow_values(true, false).for(attribute_name.to_sym) }
it { is_expected.not_to allow_value(nil).for(attribute_name.to_sym) }
it {
expect(
described_class.new(attribute_name.to_sym => nil).errors_on(attribute_name.to_sym)
).to include(options[:bool_validation_message])
} if options[:bool_validation_message]
end
@stratigos
Copy link
Author

This is an RSpec matcher to be used when you have robots uploading data (firmware, raspberry pi, IoT boards, etc), and you would like to express a specification in your data models that strictly true or false values are the only acceptable input.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment