使用kind_of?在Ruby中使用Rspec

时间:2014-09-22 15:47:05

标签: ruby rspec

我试图测试这个方法,该方法可以只使用整数作为参数,但我不能使它工作;不幸。 谢谢你的时间。 我不明白这个错误记录:

1)DownloadingData interval_data采用2个整数作为参数来设置时间间隔      失败/错误:bag.should_receive(:interval_data).with(2,kind_of(数字),kind_of?(数字),2)        (#)。interval_data(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

1 个答案:

答案 0 :(得分:0)

首先你必须在statintg之后实际使用该方法,它应该被接收,否则它将不会被接收。 receive检查方法是否实际与存根一起使用。这就是他说他收到0次的原因。 RSPEC expect message

您可以在此处查看如何使用:matching arguments

试试这个:

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 Numerics调用你的方法不会导致异常。