【问题标题】:Is there an RSpec matcher to test the number of arguments with which a class is instantiated?是否有一个 RSpec 匹配器来测试一个类实例化的参数数量?
【发布时间】:2016-08-19 01:04:15
【问题描述】:

RSpec 中是否有任何匹配器来检查一个类是否用参数实例化?

类似it { is_expected.to respond_to(:initialize).with(1).argument }

谢谢!

【问题讨论】:

    标签: ruby oop rspec tdd rspec-expectations


    【解决方案1】:

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

    但是,您需要测试.new 方法,而不是.initialize 方法,因为.initialize 是私有的。

    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
    

    【讨论】:

      【解决方案2】:

      我不能 100% 确定这是否是您要问的?默认情况下,如果该类需要参数并且您实例化不正确,它将引发 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
      

      或者,您可以在参数上使用 attr_reader 并比较 instance_variables

      【讨论】:

        猜你喜欢
        • 2020-02-17
        • 2020-12-03
        • 2022-01-14
        • 2017-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多