Skip to content

Instantly share code, notes, and snippets.

@fny
Last active August 29, 2015 14:11
Show Gist options
  • Save fny/0c2f96bc4627f63f7b12 to your computer and use it in GitHub Desktop.
Save fny/0c2f96bc4627f63f7b12 to your computer and use it in GitHub Desktop.
Sneaking invalid values past Rails' inclusion validation
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
gem 'rails', github: 'rails/rails'
gem 'arel', github: 'rails/arel'
gem 'sqlite3'
GEMFILE
system 'bundle'
end
require 'bundler'
Bundler.setup(:default)
require 'active_record'
require 'minitest/autorun'
require 'logger'
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :games do |t|
t.integer :score
end
end
Game = Class.new(ActiveRecord::Base)
class Crap
def to_i
0
end
end
class InclusionValidationTest < Minitest::Test
def teardown
Game.clear_validators!
end
def test_invalid_with_nearby_float
Game.validates_inclusion_of(:score, in: [0, 1])
assert Game.new(score: 1.1).invalid?, "1.1 isn't in the list"
end
def test_invalid_with_nonsense_string
Game.validates_inclusion_of(:score, in: [0, 1])
assert Game.new(score: 'apple').invalid?, "'apple' isn't in the list"
end
def test_invalid_with_crap_object
Game.validates_inclusion_of(:score, in: [0, 1])
assert Game.new(score: Crap.new).invalid?, "There's no crap in the list"
end
end
class InclusionInArrayWithOnlyIntegerValidationTest < Minitest::Test
def test_invalid_with_nonsense_string
Game.validates_numericality_of(:score, only_integer: true)
Game.validates_inclusion_of(:score, in: [0, 1])
game = Game.new(score: 'apple')
game.valid?
assert game.errors.added?(:score, :not_a_number)
assert game.errors.added?(:score, :inclusion), "Expected an inclusion error."
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment