Rails Rspec整数等于字符串("1"== 1)

Nic*_*ick 2 ruby integer rspec ruby-on-rails comparator

在rspec中,你如何在忽略类型的同时比较某些东西的价值?

Failure/Error: expect(variable).to eql model.id

  expected: 1234
       got: "1234"

  (compared using eql?)
Run Code Online (Sandbox Code Playgroud)

我试过eq(比较使用==)和eql(比较使用eql?)...我也读过/sf/answers/2304888631/.

如何让rspec认为这两个值相等?

Eri*_*nil 8

不同类的实例不能相等.

您需要转换它们,使它们成为同一个类的实例:

"1234" == 1234
#=> false
"1234".to_i == 1234
#=> true
1234.to_s == "1234"
#=> true
Run Code Online (Sandbox Code Playgroud)

所以在你的例子中:

expect(variable.to_i).to eql model.id
# or less logical :
expect(variable).to eql model.id.to_s
Run Code Online (Sandbox Code Playgroud)