1

Are there any matchers in RSpec to check that a class is instantiated with an argument?

Something like it { is_expected.to respond_to(:initialize).with(1).argument }

Thanks!

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
Reiss Johnson
  • 1,419
  • 1
  • 13
  • 19

2 Answers2

3

The respond_to matcher that you give as an example exists, with the exact syntax that you give.

However, you need to test the .new method, not the .initialize method, because .initialize is private.

class X
  def initialize(an_arg)
  end
end

describe X do
  describe '.new'
    it "takes one argument" do
      expect(X).to respond_to(:new).with(1).argument
    end
  end
end
Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
0

I'm not 100% sure if this is what you're asking? By default if the class requires arguments and you instantiate incorrectly it will throw an ArgumentError.

require 'rspec'

class Test
  def initialize(var)
  end
end

RSpec.describe do
  describe do
    it do
      expect(Test).to receive(:new).with('testing')
      Test.new('test')
    end
  end
end

Alternatively you could use attr_reader on your arguments and compare instance_variables.

Nabeel
  • 2,272
  • 1
  • 11
  • 14