我已经在我的Rails应用程序的测试/模型文件夹中进行了此测试:
test "has quantity" do
@i.quantity = 3
assert_equal @i.quantity, 3
end
我收到以下错误:
Expected: "3"
Actual: 3
我将值设置为整数(并且数据库列设置为整数)。这是相应的迁移:
class AddQuantityToItems < ActiveRecord::Migration
def change
add_column :items, :quantity, :integer
end
end
如果我将测试设置为:
test "has quantity" do
@i.quantity = 3
assert_equal @i.quantity, "3"
end
错误消失了。我应该这样做,还是有办法使值为整数而不是字符串? (或者这在Ruby中是否重要?)
任何想法都表示赞赏。
谢谢你的时间。
答案 0 :(得分:1)
我应该这样做吗
没有。 :)因为你的测试检测到有些不对劲。
或者有没有办法让值为整数而不是字符串?
Ruby数字有to_i
方法,例如"3".to_i #=> 3
这在Ruby中是否重要?
是的,这很重要。 Ruby以不同的方式处理数字和字符串。
你可以看到Ruby使用不同的类:
3.class #=> Fixnum
"3".class #=> String
值不相等:
3 == "3" #=> false
你能尝试一些诊断吗?当你这样做时你会得到什么......
item = Item.new
puts item.quantity.class
item.quantity = 3
puts item.quantity.class
这些......
test "has quantity" do
puts @i.class
puts @i.quantity.class
@i.quantity = 3
puts @i.quantity.class
assert_equal @i.quantity, 3
end
在您的数据库中,您可以打印测试数据库表架构吗?
MySQL示例:
desc items
我的猜测是测试数据库中的模式不是您所期望的。
通常,您可能希望尝试从测试中删除@i
,因为@
符号表示@i
是来自某个特定测试之外某处的实例变量。< / p>
例如:
test "has quantity" do
i = Item.new
i.quantity = 3
assert_equal i.quantity, 3
end