Rails测试因fixture而失败,但是直接创建了对象

时间:2016-12-11 03:32:45

标签: ruby-on-rails ruby unit-testing

我有一个测试:

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

它使用这个装置:

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

我的Gift模型如下所示:

validates :estimated_price,
        presence: true,
        numericality: true 

所以我期待测试通过,因为'对象'不是数字,导致@gift.save返回false并导致assert_not最终返回true。但是,由于某种原因,测试失败了。当我使用创建礼物对象的直接方式时,测试看起来像这样,测试通过:

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

我对夹具做错了什么?

1 个答案:

答案 0 :(得分:0)

您可以尝试更改验证:

function rename_appending_unique_id($source, $tempfile){

    $target_path ='uploads-unique-id/'.$source;
     while(file_exists($target_path)){
        $fileName = uniqid().'-'.$source;
        $target_path = ('uploads-unique-id/'.$fileName);
    }

    move_uploaded_file($tempfile, $target_path);

}

if(isset($_FILES['upload']['name'])){

    $sourcefile= $_FILES['upload']['name'];
    tempfile= $_FILES['upload']['tmp_name'];

    rename_appending_unique_id($sourcefile, $tempfile);

}