在 Rails 模型测试中出现错误 - 预期为“3”实际为 3

Getting an Error in Rails Model Test - Expected "3" Actual 3

我的 Rails 应用的 test/models 文件夹中有这个测试:

  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 中是否重要?)

如有任何想法,我们将不胜感激。

谢谢你的时间。

Should I just do this

没有。 :) 因为您的测试检测到有问题。

Or is there a way to make the value an integer instead of a string?

Ruby 数字有一个方法 to_i,例如 "3".to_i #=> 3

Does this even matter in 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

并且在您的数据库中,您可以打印测试数据库 table 模式吗?

MySQL 示例:

desc items

我猜你在测试数据库中的架构不是你所期望的。

一般来说,您可能想尝试从测试中删除 @i,因为 @ 符号意味着 @i 是来自特定测试之外某处的实例变量.

例如:

test "has quantity" do
  i = Item.new
  i.quantity = 3
  assert_equal i.quantity, 3
end