简体   繁体   English

Rails测试因夹具失败,但通过直接对象创建而通过

[英]Rails test fails with fixture but passes with direct object creation

I have a test: 我有一个测试:

test 'gift should not be saved with a non-numeric price' do
  @gift = gifts(:gift_without_numeric_price)
  assert_not @gift.save, 'gift was saved with non-numeric name'
end

It uses this fixture: 它使用以下夹具:

gift_without_numeric_price:
  name: "pinecones"
  description: "these pinecones smell really good"
  estimated_price: "object"
  link: "www.google.com"

My Gift model looks like this: 我的Gift模型如下所示:

validates :estimated_price,
        presence: true,
        numericality: true 

So I was expecting the test to pass since 'object' is not numeric, causing the @gift.save to return false and causing the assert_not to ultimately return true. 因此,我期望测试能够通过,因为“对象”不是数字,导致@gift.save返回false,并导致assert_not最终返回true。 However, the test fails for some reason. 但是,由于某种原因,测试失败。 When I use the the direct way of creating a gift object, the test looks like this and the test passes: 当我使用直接创建礼物对象的方式时,测试看起来像这样,测试通过:

test 'gift should not be saved with a non-numeric price' do
  @gift = Gift.new(name: 'aa', description: 'description', link: 'www.google.com', estimated_price: 'object')
  assert_not @gift.save, 'gift was saved with non-numeric name'
end

What am I doing wrong with the fixture? 我的灯具在做什么错?

您可以尝试更改验证:

validates :estimated_price, presence: true,numericality: { only_integer: true }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM