summaryrefslogtreecommitdiff
path: root/spec/support/helpers/after_next_helpers.rb
blob: 0a7844fdd8f391af8649bb25b59722daf699de34 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# frozen_string_literal: true

require_relative './next_instance_of'

module AfterNextHelpers
  class DeferredExpectation
    include ::NextInstanceOf
    include ::RSpec::Matchers
    include ::RSpec::Mocks::ExampleMethods

    def initialize(klass, args, level:)
      @klass = klass
      @args = args
      @level = level.to_sym
    end

    def to(condition)
      run_condition(condition, asserted: true)
    end

    def not_to(condition)
      run_condition(condition, asserted: false)
    end

    private

    attr_reader :klass, :args, :level

    def run_condition(condition, asserted:)
      msg = asserted ? :to : :not_to
      case level
      when :expect
        if asserted
          expect_next_instance_of(klass, *args) { |instance| expect(instance).send(msg, condition) }
        else
          allow_next_instance_of(klass, *args) { |instance| expect(instance).send(msg, condition) }
        end
      when :allow
        allow_next_instance_of(klass, *args) { |instance| allow(instance).send(msg, condition) }
      else
        raise "Unknown level: #{level}"
      end
    end
  end

  def allow_next(klass, *args)
    DeferredExpectation.new(klass, args, level: :allow)
  end

  def expect_next(klass, *args)
    DeferredExpectation.new(klass, args, level: :expect)
  end
end