I have a table (Dishes) that has a column (nutrition_facts) that stores key/value data (similar to hstore in a PostgreSQL database).
I’ve defined a new instance of a Dish in my fixtures folder as such:
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
But I can’t seem to make the following assertions work when I run rake test:units — it fails on the first 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
How can I test for the individual calories and serving_size values without testing the entire nutrition_facts field?
In short, I’m trying to test the following validation (from my dish.rb file), which works when I run the application in a browser:
# Check 'serving size' isn't blank only if 'calories' is defined
validates_presence_of :serving_size, :if => Proc.new { |val| !val.calories.blank? }
I was able to get it to work by doing defining my nutrition_facts column’s key/value as such:
So in my fixtures, it’ll look like this:
With my unit test now looking like this:
Source: Fixtures and serialized attributes in Ruby on Rails