# frozen_string_literal: true require "spec_helpers" describe Wayfarer::Networking::Context do let(:instance) { Object.new } let(:strategy) { spy } let(:renewing_error) { Class.new(StandardError) } subject(:context) { Wayfarer::Networking::Context.new(strategy) } before do allow(strategy).to receive(:renew_on).and_return([renewing_error]) allow(strategy).to receive(:create).and_return(instance) end describe "#new" do it "assigns the strategy" do expect(context.strategy).to be(strategy) end it "assigns the instance" do expect(context.strategy).to be(strategy) end end describe "#fetch" do let(:url) { Object.new } it "fetches" do expect(strategy).to receive(:fetch).with(instance, url) context.fetch(url) end context "with renewing exception raised" do before do allow(strategy).to receive(:fetch).and_raise(renewing_error) end it "renews and reraises" do expect(context).to receive(:renew) expect { context.fetch(url) }.to raise_error(renewing_error) end end context "with configured renewing exception raised" do let(:other_error) { Class.new(StandardError) } before do Wayfarer.config.network.renew_on = [other_error] allow(strategy).to receive(:fetch).and_raise(other_error) end it "renews and reraises" do expect(context).to receive(:renew) expect { context.fetch(url) }.to raise_error(other_error) end end context "with non-renewing exception raised" do before do allow(strategy).to receive(:fetch).and_raise(StandardError) end it "reraises" do expect(context).not_to receive(:renew) expect { context.fetch(url) }.to raise_error(StandardError) end end end describe "#live" do let(:page) { Object.new } it "calls live" do expect(strategy).to receive(:live).with(instance) context.live end context "with renewing exception raised" do before do allow(strategy).to receive(:live).and_raise(renewing_error) end it "renews and reraises" do expect(context).to receive(:renew) expect { context.live }.to raise_error(renewing_error) end context "when renewing raises" do let(:other_error) { Class.new(StandardError) } before do allow(context).to receive(:renew).and_raise(other_error) end it "reraises the original exception" do expect { context.live }.to raise_error(renewing_error) end end end context "with non-renewing exception raised" do before do allow(strategy).to receive(:live).and_raise(StandardError) end it "reraises" do expect(context).not_to receive(:renew) expect { context.live(page) }.to raise_error(StandardError) end end end describe "#renew" do it "destroys" do expect(strategy).to receive(:destroy).with(instance) context.renew end end describe "#instance" do it "creates an instance" do expect(strategy).to receive(:create).and_return(instance) expect(context.instance).to be(instance) end end end