1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Parallel gemで実装した処理をRspecでは同じスレッド上で動かす

Posted at

以下のようにParallelにて処理を並列スレッドで実行しているとき、

hoges_controller.rb
def index
    procs = [
        -> { hoge1 },
        -> { hoge2 },
        -> { hoge3 }
    ]
    result = Parallel.map(procs, in_threads: 3, &:call)
end

Rspecではletやsubjectが変数に対してロックを獲得するため、複数スレッドで変数の参照待ちになりデッドロックが発生し、テストが永遠に終わらなくなってしまう

それを解決するために、Rspec上では直列で処理を実行するようParallelをモックして、ブロックを呼び出すだけにする

hoges_controller_spec.rb
describe '#index' do
    subject { get hoges_path }

    # Parallel.mapの引数で渡された配列をmapしてcallするだけ
    before { allow(Parallel).to receive(:map) { |procs| procs.map(&:call) } }

    it_behaves_like 'return success'
end
1
0
1

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?