Skip to content

Instantly share code, notes, and snippets.

@stellard
Created May 26, 2012 20:59
Show Gist options
  • Save stellard/2795294 to your computer and use it in GitHub Desktop.
Save stellard/2795294 to your computer and use it in GitHub Desktop.
ensure_inclusion_of_spec.rb
require 'rspec'
require 'rails'
require 'shoulda-matchers'
CORRECT_ARRAY = %w(one two three)
WRONG_ARRAY = %w(wrong array)
class Nothing
include ActiveModel::Validations
attr_accessor :array_to_test
end
class Something
include ActiveModel::Validations
attr_accessor :array_to_test
validates :array_to_test, :inclusion => { :in => CORRECT_ARRAY }
end
describe Nothing do
it { should_not ensure_inclusion_of(:array_to_test).in_array(CORRECT_ARRAY) } #=> this should pass. There is no validation.
it { should_not ensure_inclusion_of(:array_to_test).in_array(WRONG_ARRAY) } #=> this should pass. There is no validation.
end
describe Something do
it { should ensure_inclusion_of(:array_to_test).in_array(CORRECT_ARRAY) } #=> this does pass. but will not fail if validation is removed.
it { should_not ensure_inclusion_of(:array_to_test).in_array(WRONG_ARRAY) } #=> this does pass, but only verifies a small subset of invalid values.
end
# $ bundle exec rspec ensure_inclusion_spec.rb
#
# Nothing
# should not ensure inclusion of array_to_test in ["one", "two", "three"] (FAILED - 1)
# should not ensure inclusion of array_to_test in ["wrong", "array"] (FAILED - 2)
#
# Something
# should ensure inclusion of array_to_test in ["one", "two", "three"]
# should not ensure inclusion of array_to_test in ["wrong", "array"]
#
# Failures:
#
# 1) Nothing
# Failure/Error: it { should_not ensure_inclusion_of(:array_to_test).in_array(CORRECT_ARRAY) } #=> this should pass. There is no validation.
# Did not expect errors when array_to_test is set to "three", got error:
# # ./test_spec.rb:23:in `block (2 levels) in <top (required)>'
#
# 2) Nothing
# Failure/Error: it { should_not ensure_inclusion_of(:array_to_test).in_array(WRONG_ARRAY) } #=> this should pass. There is no validation.
# Did not expect errors when array_to_test is set to "array", got error:
# # ./test_spec.rb:24:in `block (2 levels) in <top (required)>'
#
# Finished in 0.09288 seconds
# 4 examples, 2 failures
#
# Failed examples:
#
# rspec ./test_spec.rb:23 # Nothing
# rspec ./test_spec.rb:24 # Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment