🖥
#rspec で allow_any_instance_of / expect_any_instance_of が非推奨な理由
何?
- ひとつのクラスのすべてのインスタンス+特定メソッドに対して expect / allow してしまうので、単純に、エッジケースをカバーできないでしょう (同じクラスが2個以上のインスタンス生成・メソッド実行する場合はどうするの?)
- allow_any_instance_of / expect_any_instance_of を使うということはそもそも、テストがやりすぎか、複雑で乱れているケースでは?
- rspec-mocks で多くのバグレポートが上がった歴史があるらしい
というようなことが書いてある気がした。
Doc
Settings mocks or stubs on any instance of a class
rspec-mocks provides two methods, allow_any_instance_of and expect_any_instance_of, that will allow you to stub or mock any instance of a class. They are used in place of allow or expect:
allow_any_instance_of(Widget).to receive(:name).and_return("Wibble")
expect_any_instance_of(Widget).to receive(:name).and_return("Wobble")
These methods add the appropriate stub or expectation to all instances of Widget.
This feature is sometimes useful when working with legacy code, though in general we discourage its use for a number of reasons:
- The rspec-mocks API is designed for individual object instances, but this feature operates on entire classes of objects. As a result there are some semantically confusing edge cases. For - example in expect_any_instance_of(Widget).to receive(:name).twice it isn't clear whether each specific instance is expected to receive name twice, or if two receives total are expected. (It's the former.)
- Using this feature is often a design smell. It may be that your test is trying to do too much or that the object under test is too complex.
- It is the most complicated feature of rspec-mocks, and has historically received the most bug reports. (None of the core team actively use it, which doesn't help.)
rspec/rspec-mocks: RSpec's 'test double' framework, with support for stubbing and mocking
Original by Github issue
チャットメンバー募集
何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。
公開日時
2020-04-24
Discussion