RuboCop::Cop::RSpec::AnyInstance
に引っかかってしまった。
これは、rubydocを参照すると、次のような例が書いてある。
https://www.rubydoc.info/gems/rubocop-rspec/1.37.0/RuboCop/Cop/RSpec/AnyInstance
# bad
describe MyClass do
before { allow_any_instance_of(MyClass).to receive(:foo) }
end
# good
describe MyClass do
let(:my_instance) { instance_double(MyClass) }
before do
allow(MyClass).to receive(:new).and_return(my_instance)
allow(my_instance).to receive(:foo)
end
end
つまりallow_any_instance_of
を使うなって話で、理由はrspec開発チームが述べている。
https://relishapp.com/rspec/rspec-mocks/docs/working-with-legacy-code/any-instance
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.)
お、、お疲れ様・・。
というわけで、allow_any_instance_ofを次の手順で書き換えると良い。
- 対象クラスのinstance_doubleを作成する。
- allowを使用して作成したinstance_doubleを対象クラスのnewで返すようにする
- allowを使用して、instance_doubleのテストしたいメソッドをテストする。
ちょっと書く量が増えるけど、allow_any_instance_ofって怪しい動きをすることもあったしこれがいいかな。