用什么?在Ruby中使用Rspec

用什么?在Ruby中使用Rspec,ruby,rspec,Ruby,Rspec,我正在尝试测试这个方法,这个方法只能把整数作为参数,但我不能让它工作;不幸的是。 谢谢你抽出时间。 我不明白这个错误日志: 1) DownloadingData interval\u数据采用2个整数作为参数来设置时间间隔 失败/错误:行李应接收(:间隔数据)。带有(2,种类(数字),种类(数字),2) (#)。间隔#u数据(2,#,false,2) 应为:1次带参数:(2,#,false,2) 收到:0次,带参数:(2,#,false,2) 我的代码: class DownloadingData

我正在尝试测试这个方法,这个方法只能把整数作为参数,但我不能让它工作;不幸的是。 谢谢你抽出时间。 我不明白这个错误日志:

1) DownloadingData interval\u数据采用2个整数作为参数来设置时间间隔 失败/错误:行李应接收(:间隔数据)。带有(2,种类(数字),种类(数字),2) (#)。间隔#u数据(2,#,false,2) 应为:1次带参数:(2,#,false,2) 收到:0次,带参数:(2,#,false,2)

我的代码:

class DownloadingData

  attr_accessor :today

  def initialize
    @today = Date.today
  end

  def interval_data(point_a, point_b)
    start_point = @today - point_a
    end_point  = @today + point_b
    (start_point..end_point).each do |week_day|
      puts week_day #checking the week day
    end
  end
end
我的测试:

describe DownloadingData do
   let(:bag) { DownloadingData.new }

  describe 'interval_data' do
    it 'responds to interval_data' do
      expect(bag).to respond_to(:interval_data)
    end
    it 'takes 2 integers as parameters to set up the time-interval' do
      bag.should_receive(:interval_data).with(2, kind_of(Numeric), kind_of?(Numeric), 2)
    end
end

首先,您必须实际使用该方法,然后确定应该接收该方法,否则将不接收该方法
receive
检查方法是否实际用于存根。这就是为什么他说他收到了0次

在这里,您可以看到如何使用with:

试试这个:

it 'takes 2 integers as parameters to set up the time-interval' do
  expect(bag).to receive(:interval_data).with(kind_of(Numeric), kind_of(Numeric)).and_call_original
  bag.interval_data(1, 2)
end

尽管这只会验证使用2个数字调用方法不会导致异常。

尽管该规范实际上没有做任何事情,但它验证了interval\u data方法使用2个数字运行时没有错误。不是真的需要这样测试,但这就是我们要求的。@ascar Hi!谢谢你的回复!u说:“真的没有必要这样测试它”那么怎么测试呢?谢谢只有当此方法是从另一个方法中动态调用的,并且您希望确保代码在另一个方法更改时工作时,测试正确类型的输入才有意义。如果方法没有抛出异常,我提供的规范将始终有效,因为我在规范期间明确提供了工作输入.not_引发错误也会发生同样的事情。@ascar方法调用通过使用
receive
-未测试原始实现您可能不想在此处使用should_receive。而是调用该方法并指定返回值应该是什么(或者应该发生什么副作用)