# frozen_string_literal: true require "spec_helpers" describe Wayfarer::Middleware::Chain do let(:task) { build(:task) } subject(:chain) { described_class.new(middlewares) } describe "#call" do context "without middlewares" do let(:middlewares) { [] } it "does not raise" do expect { chain.call(task) }.not_to raise_error end it "yields" do expect { |spy| chain.call(task, &spy) }.to yield_control end end context "when middleware yields" do let(:middlewares) { [spy, spy] } it "yields" do allow(middlewares.first).to receive(:call).and_yield expect(middlewares.last).to receive(:call).with(task).and_yield expect { |spy| chain.call(task, &spy) }.to yield_control end end context "when middleware does not yield" do let(:middlewares) { [spy, spy] } it "does not yield" do allow(middlewares.first).to receive(:call) expect(middlewares.last).not_to receive(:call) expect { |spy| chain.call(task, &spy) }.not_to yield_control end end describe "Immutability" do let(:middlewares) { [spy, spy] } it "does not alter its middleware" do allow(middlewares.first).to receive(:call).and_yield allow(middlewares.second).to receive(:call).and_yield expect { chain.call(task) }.not_to(change { chain.middlewares }) end end describe "Return value" do let(:middlewares) do [build(:middleware, receiver: lambda do |task, &block| task.metadata.foobar = 42 block.call end), build(:middleware, receiver: lambda do |task| task.metadata.foobar *= 1337 end)] end it "is the last middleware's return value" do expect(chain.call(task)).to be(56_154) end end describe "Metadata" do let(:first) do build(:middleware, receiver: lambda do |task, &block| task.metadata.foobar = 42 block.call task.metadata.barqux = 1337 end) end let(:last) do build(:middleware, receiver: lambda do |task| raise unless task.metadata.foobar == 42 raise if task.metadata.barqux end) end let(:middlewares) { [first, last] } it "is accessible across middleware" do expect { chain.call(task) }.not_to raise_error expect(task.metadata.foobar).to be(42) expect(task.metadata.barqux).to be(1337) end end end end