例えばActiveRecordで新規作成したタイミングでリモートにアクセスするような処理があったとして
class Item <ActiveRecord::Base
before_create :do_something_with_remote
def do_something_with_remote
open(self.url)
end
end
before_create :do_something_with_remote
def do_something_with_remote
open(self.url)
end
end
この場合、テストの時はItem#do_something_with_remoteをスタブにするよね。
item = Item.new :url => 'http://www.example.com'
item.stub! :do_something_with_remote
item.stub! :do_something_with_remote
本当はこんな感じでかけたい
Item.stub_instance_method(:do_something_with_remote)
stubはそのオブジェクトにしか使えない?インスタンスメソッドまで影響するスタブはどう書けば良い?
--
Fixtureの代わりにFactoryGirlを使い始めた。 これがなかなかシンプルで使い勝手が良いんだけど、関連を設定する時に上記のような作りの場合にちょっと困っている。 Factory.defineの中でインスタンスのメソッドにstubを設定できればいいんだよな。
Factory.define :item, :class => Item do |item|
item.stub!(:do_something_with_remote)
end
item.stub!(:do_something_with_remote)
end
明日改造できるかソースコードを見てみる。 Factory.stubはあるんだし、できないことはないよな。
今は時間がないのでスペックヘルパーで
class Item
def do_something_remote;end
end
def do_something_remote;end
end
みたいに上書きして対処しているが・・・駄目だよな。
FactoryGirlに関してはノウハウが溜まったら書くかも。