Rails 5.2 Rspec 3.8 - 为什么十进制模型属性转换为字符串?
Rails 5.2 Rspec 3.8 - Why is decimal model attribute converting to string?
我有这样的迁移:
class AddScoreToContact < ActiveRecord::Migration[5.2]
def change
add_column :contacts, :score, :decimal, precision: 4, scale: 3, default: 0
end
end
当我尝试这样测试时:
contact = Contact.new(score: 0.5)
puts contact.score.class # **outputs String**
it 'is between 0 and 1' do
expect(contact.score).to be_between(0, 1)
end
测试失败,除非我调用 contact.score.to_f
为什么是字符串?
测试输出:
Failure/Error: expect(contact.score).to be_between(0, 1)
expected "0.5" to be between 0 and 1 (inclusive)
编辑
模型验证是:
validates :score, presence: true
validates :score, numericality: { greater_than_or_equal_to: 0,
less_than_or_equal_to: 1 }
此问题的解决方案是删除数据库,重新创建它,然后再次 运行 迁移。之后就不再转字符串了
奇怪的是,这应该可以解决问题,因为测试根本不涉及数据库(它使用 new
而不是 create
来创建被测对象)。
我只能得出结论,在处理此问题的过程中,测试数据库最终处于不一致的状态,并且以某种方式泄漏到测试中。
我有这样的迁移:
class AddScoreToContact < ActiveRecord::Migration[5.2]
def change
add_column :contacts, :score, :decimal, precision: 4, scale: 3, default: 0
end
end
当我尝试这样测试时:
contact = Contact.new(score: 0.5)
puts contact.score.class # **outputs String**
it 'is between 0 and 1' do
expect(contact.score).to be_between(0, 1)
end
测试失败,除非我调用 contact.score.to_f
为什么是字符串?
测试输出:
Failure/Error: expect(contact.score).to be_between(0, 1)
expected "0.5" to be between 0 and 1 (inclusive)
编辑
模型验证是:
validates :score, presence: true
validates :score, numericality: { greater_than_or_equal_to: 0,
less_than_or_equal_to: 1 }
此问题的解决方案是删除数据库,重新创建它,然后再次 运行 迁移。之后就不再转字符串了
奇怪的是,这应该可以解决问题,因为测试根本不涉及数据库(它使用 new
而不是 create
来创建被测对象)。
我只能得出结论,在处理此问题的过程中,测试数据库最终处于不一致的状态,并且以某种方式泄漏到测试中。