Module: Saharspec::Its::Call

Defined in:
lib/saharspec/its/call.rb

Instance Method Summary collapse

Instance Method Details

#its_call(*args, &block) ⇒ Object

For #call-able subject, creates nested example where subject is called with arguments provided, allowing to apply block matchers like .to change(something) or .to raise_error to different calls in a DRY way.

Also, plays really well with #ret block matcher.

Examples:

let(:array) { %i[a b c] }

describe '#[]' do
  subject { array.method(:[]) }

  its_call(1) { is_expected.to ret :b }
  its_call(1..-1) { is_expected.to ret %i[b c] }
  its_call('foo') { is_expected.to raise_error TypeError }
end

describe '#push' do
  subject { array.method(:push) }
  its_call(5) { is_expected.to change(array, :length).by(1) }
end


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/saharspec/its/call.rb', line 26

def its_call(*args, &block)
  # rubocop:disable Lint/NestedMethodDefinition
  describe("(#{args.map(&:inspect).join(', ')})") do
    let(:__call_subject) do
      warn 'No need to use its_call without arguments, just it {} will work' if args.empty?
      -> { subject.call(*args) }
    end

    def is_expected
      expect(__call_subject)
    end

    example(nil, &block)
  end
  # rubocop:enable Lint/NestedMethodDefinition
end