Skip to content

Instantly share code, notes, and snippets.

@tiegz
Last active August 6, 2017 16:34
Show Gist options
  • Save tiegz/db9a6b057ea85f1784750aa6aa757bac to your computer and use it in GitHub Desktop.
Save tiegz/db9a6b057ea85f1784750aa6aa757bac to your computer and use it in GitHub Desktop.
Rails 5.0 numericality with_integer: true bug
# Run in Rails 5.0 active_record folder with:
# bundle exec rake test:sqlite3 TEST=test/cases/attribute_test.rb
require 'cases/helper'
class PriceEstimate < ActiveRecord::Base
validates :price, presence: true, numericality: { only_integer: true }
# Accepts float (1.23), rounds it (1.0), stores it as integer (1).
def price=(float_val)
int_val = float_val.round
write_attribute(:price, int_val)
end
# Fetches the integer value (1) and returns decimal (1.0).
def price
read_attribute(:price).to_d
end
end
module ActiveRecord
class NumericalityTest < ActiveRecord::TestCase
test "numericality with only_integer, on class with reader/writers overwritten" do
price_estimate = PriceEstimate.new(price: 1).tap(&:validate)
assert_equal 1.to_d, price_estimate.price
assert_equal [], price_estimate.errors[:price]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment