テストでスタブの掛け方に悩み中

このエントリーを含むはてなブックマーク

例えばActiveRecordで新規作成したタイミングでリモートにアクセスするような処理があったとして

  1. class Item <ActiveRecord::Base
  2.   before_create :do_something_with_remote
  3.   def do_something_with_remote
  4.     open(self.url)
  5.   end
  6. end


この場合、テストの時はItem#do_something_with_remoteをスタブにするよね。

  1. item = Item.new :url => 'http://www.example.com'
  2. item.stub! :do_something_with_remote


本当はこんな感じでかけたい

  1. Item.stub_instance_method(:do_something_with_remote)


stubはそのオブジェクトにしか使えない?インスタンスメソッドまで影響するスタブはどう書けば良い?

--

Fixtureの代わりにFactoryGirlを使い始めた。 これがなかなかシンプルで使い勝手が良いんだけど、関連を設定する時に上記のような作りの場合にちょっと困っている。 Factory.defineの中でインスタンスのメソッドにstubを設定できればいいんだよな。

  1. Factory.define :item, :class => Item do |item|
  2.   item.stub!(:do_something_with_remote)
  3. end


明日改造できるかソースコードを見てみる。 Factory.stubはあるんだし、できないことはないよな。

今は時間がないのでスペックヘルパーで

  1. class Item
  2.   def do_something_remote;end
  3. end


みたいに上書きして対処しているが・・・駄目だよな。
FactoryGirlに関してはノウハウが溜まったら書くかも。

Posted in ruby on rails at 4月 24th, 2009. Trackback URI: trackback
Tags: , ,

No Responses to “テストでスタブの掛け方に悩み中”

Leave a Reply