4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

コード変更前のテストデータを作る方法

Posted at

概要

コードの一部を変更した結果、コード変更前のデータ、変更後のデータができます。
変更後のデータは容易に作成できるのでテストしやすいのですが、コード変更前のデータでも問題無く動作することをどうやってテストしようか、という話題です。

やり方

色々あると思いますが、旧コードを特異メソッドとして定義して、オーバーライドしてみました。
factory_girlにはafter(:build)というhookがあって、ActiveRecordのafter_initializeのようなタイミングで呼ばれます。
テストコードによってはafter(:create)とかでも良いと思いますが、今回はsave前にhookする必要があったのでafter(:build)にしました。

factories/cart.rb
FactoryGirl.define do
  factory :cart do
    factory :cart_with_old_tax do
      after(:build) do |cart, evaluator|
        # Cart#price_with_taxはprice + ConsumptionTax.calc(price)に変更されている
        def cart.price_with_tax
          price + OldConsumptionTax.calc(price)
        end
      end
    end
  end
end
spec/cart_spec.rb
describe Cart do
  describe '#price_with_tax' do
    let(:cart) { create(:cart_with_old_tax) } # 旧コードのインスタンス
    subject { Cart.find(cart.id) } # 新コードのインスタンス
  end
end

おわりに

上記の例では旧税率のデータを作ればいいだけなんですが、factory_girlbefore_validationを無視してデータを作る方法が分からなかったのでこんな感じでやってみました。
バッドノウハウの匂いがします。
直接DML投げてデータ作れれば楽なんですけどねぇ…

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?