Rails宝典の第60式:fixturesを使わないテスト


fixturesに大きく依存するテストは脆弱になり、メンテナンスが困難になります.
fixturesを使用しないテストを書く方法を見てみましょう.
cart/lineを見てitemの例:

class Cart < ActiveRecord::Base
  has_many :line_items

  def total_weight
    line_items.to_s.sum(&:weight)
  end
end

class LineItem < ActiveRecord::Base
  belongs_to :cart
  belongs_to :product
  belongs_to :delivery_method

  def weight
    if delivery_method.shipping?
      product.weight*quantity
    else
      0
    end
  end
end

簡単なフィールドデータに対してActiveRecordで生成したbuild_xxxメソッドはフィールドに値を割り当ててテストします.

class LineItemTest < Test::Unit::TestCase
  def test_should_have_zero_for_weight_when_not_shipping
    line_item = LineItem.new
    line_item.build_delivery_method(:shipping => false)
    assert_equal 0, line_item.weight
  end

  def test_should_have_weight_of_product_times_quantity_when_shipping
    line_item = LineItem.new(:quantity => 3)
    line_item.build_delivery_method(:shipping => true)
    line_item.build_product(:weight => 5)
    assert equal 15, line_item.weight
  end
end

しかし、次のテストを検討します.

class CartTest < Test::Unit::TestCase
  fixtures :carts, :line_items, :delivery_methods, :products

  def test_total_weight
    assert_equal 10, carts(:primary).total_weight
  end
end

ここではcart/lineを手動で準備します.itemデータは面倒でtotal_Weightはlineに依存するitem.Weightメソッド、weightメソッドはテスト済みです
面倒を減らすために、fixturesを必要とせずにmock方式を使用してテストを簡素化することができます.
まずmochaをインストールする必要があります

sudo gem install mocha

そしてtest_helper.rb里require mocha:

require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require 'test_help'
require 'mocha'

私たちはこのようにmochaを使ってCartTestを書きます.

require File.dirname(__FILE__) + '/../test_helper'

class CartTest < Test::Unit::TestCase
  def test_total_weight_should_be_sum_of_line_item_weights
    cart = Cart.new
    cart.line_items.build.stubs(:weight).returns(7)
    cart.line_items.build.stubs(:weight).returns(3)
    assert_equal 10, cart.total_weight
  end
end

Weightメソッドは既に測定されているため、ここではstubsシミュレーションweightメソッドの戻り値を使用して、テストロジックをtotal_に集中する.Weightメソッド