Rails 4 - 为包含配置值的方法编写单元测试

时间:2016-03-10 13:07:33

标签: ruby-on-rails unit-testing

我刚刚开始在Rails中编写一些单元测试,我遇到的一个问题是我应该如何测试包含配置数据的方法。

config.yml

drink_category_defaults:
1: #beer
  brand_id: 103 # 4.5%
  volume_id: 5 # Pint
  price: 300
2: #wine
  brand_id: 207 # 12%
  volume_id: 16 # Medium glass (175ml)
  price: 300
3: #cider
  brand_id: 304 # 4.5%
  volume_id: 12 # Pint
  price: 300
4: #spirits
  brand_id: 406 # 40%
  volume_id: 31 # Large single (35ml)
  price: 250
5: #alcopops
  brand_id: 502 # 4.5%
  volume_id: 52 # Standard bottle (275ml)
  price: 250
6: #champagne
  brand_id: 607 # 12%
  volume_id: 20 # Flute (150ml)
  price: 400

方法:

def self.new_with_defaults_for_category category_id
  drink = Drink.new
  category_defaults = APP_CONFIG['drink_category_defaults'][category_id.to_i]
  if category_defaults
    drink.drink_category_id = category_id
    drink.drink_brand_id = category_defaults['brand_id']
    drink.drink_volume_id = category_defaults['volume_id']
    drink.cost_per_drink = category_defaults['price']
  end
  drink
end

我目前的测试:

# self.new_with_defaults_for_category
test "should return a new drink object with category defaults" do
  6.times do |i|
    i += 1
    drink = Drink.new_with_defaults_for_category(i)
    assert_instance_of(Drink, drink)
    assert drink.drink_category_id === i
    assert drink.drink_brand_id.present?
    assert drink.drink_volume_id.present?
    assert drink.cost_per_drink.present?
  end
end

我觉得我会以错误的方式解决这个问题。我可能不应该使用真正的配置数据,并且应该以某种方式模拟测试。除此之外,仅检查属性是否存在是不够的,并且通过检查实际属性值,测试需要尽可能具体。

非常感谢能够采取最佳方法来解决这个问题。非常感谢。

0 个答案:

没有答案