1

我有一个表 ( Dishes),其中有一列 ( nutrition_facts),用于存储键/值数据(类似于hstorePostgreSQL数据库)。

我在我的fixtures文件夹中定义了一个新的Dish实例:

nutrition_facts:
  id: 6
  name: Dish 6
  category: Cat 1
  description: Something about Dish 6
  price: 15.32
  menu_id: 1
  nutrition_facts:
    serving_size:
    calories: 392

但是当我运行时,我似乎无法使以下断言起作用rake test:units——它在第一次失败assert_not_nil

  test "no serving size with calories" do
    dish = dishes(:nutrition_facts)

    assert_not_nil(dish.calories)
    assert_nil(dish.serving_size)
    assert !dish.save, "Saved dish when serving size wasn't defined while calories was"
  end

如何在不测试整个字段的情况下测试个人calories和价值观?serving_sizenutrition_facts

简而言之,我正在尝试测试以下验证(来自我的dish.rb文件),当我在浏览器中运行应用程序时该验证有效:

  # Check 'serving size' isn't blank only if 'calories' is defined
  validates_presence_of :serving_size, :if => Proc.new { |val| !val.calories.blank? }
4

1 回答 1

1

我能够通过定义我的 Nutrition_facts 列的键/值来使其工作:

nutrition_facts: <%= {:serving_size => nil, :calories => 33}.to_yaml.inspect %>

所以在我的装置中,它看起来像这样:

nutrition_facts:
  id: 6
  name: Dish 6
  category: Cat 1
  description: Something about Dish 6
  price: 15.32
  menu_id: 1
  nutrition_facts: <%= {:serving_size => nil, :calories => 33}.to_yaml.inspect %>

我的单元测试现在看起来像这样:

  test "no serving size with calories" do
    dish = dishes(:nutrition_facts)

    assert_not_nil(dish.calories)
    assert_nil(dish.serving_size)
    assert !dish.save, "Saved dish when serving size wasn't defined while calories was"
  end

来源:Ruby on Rails 中的固定装置和序列化属性

于 2012-07-10T21:51:31.513 回答