RSpec:似乎无法存根ActiveRecord :: QueryMethods #select

时间:2015-07-23 19:55:17

标签: ruby-on-rails ruby activerecord rspec stub

我正在尝试编写一个测试来计算许多db记录的平均值而不会实际读取/写入db的开销。

以下是方法:

class Average::Route
  def self.daily_flight_count
    Route.active.map do |r|
      times = r.flights.select('distinct depart_time').count
      (times / 7.0).round
    end.average
  end
end

该方法获取所有路线每天的唯一出发时间数,并将其平均值以获得平均路线的每日航班次数。

我正在设置我的测试:

require 'rails_helper'

describe Average::Route do
  describe '.daily_flight_count' do
    it 'returns the average daily flight count of all routes' do
      flights1 = (1..7).inject([]) do |arr, n|
        arr << double(Flight, depart_time: Time.now + n.days)
      end

      flights2 = (1..7).inject([]) do |arr, n|
        arr << double(Flight, depart_time: Time.now + n.days)
        arr << double(Flight, depart_time: Time.now + n.days)
      end

      r1 = double(Route, flights: flights1)
      r2 = double(Route, flights: flights2)

      allow(Route).to receive(:active).and_return([r1, r2])
      allow(flights1).to receive(:select).and_return(flights1.map(&:depart_time))
      allow(flights2).to receive(:select).and_return(flights2.map(&:depart_time))

      expect(Average::Route.daily_flight_count).to eq(1)
    end
  end
end

基于r1r2是如何将Route设置为返回Flight双精度数组的两倍,我遇到了一个问题,因为数组响应#select的方式与ActiveRecord Relation不同(它是如何表现的,所以我试图将flights1flights2数组存根以返回它们的映射离开时间。但是,当我运行测试时,我仍然会收到此错误:

Failures:

  1) Average::Route.daily_flight_count returns the average daily flight count of all routes
     Failure/Error: expect(Average::Route.daily_flight_count).to eq(1)
     ArgumentError:
       Wrong number of arguments. Expected 0, got 1.
     # ./app/models/average/route.rb:14:in `block in daily_flight_count'
     # ./app/models/average/route.rb:13:in `map' 

flights1flights2的存根似乎不起作用。该错误仍然在我的双打数组上调用ActiveRecord #select方法而失败,因为Array#select占用了一个块并且我的代码为它提供了一个参数(因为在生产中,集合将是一个关系)。

有关如何使这项工作的任何想法?

1 个答案:

答案 0 :(得分:0)

您需要指定您期望的参数

 allow(flights1).to receive(:select).with('distinct depart_time').and_return(flights1.map(&:depart_time))