RSpec:模拟链式数据库查询的最佳方式

时间:2016-07-18 20:36:11

标签: ruby-on-rails ruby rspec

我有以下查询:

Trainee.select(:name, :employee_start_date, :exit_date, "count(reviewers.code_review_id) AS reviews_completed")
            .where(user_id: user_ids)
            .joins(:reviewers)
            .where(reviewers: { completion_time: start_date..end_date })
            .group('trainees.user_id').order('reviews_completed DESC')

我是rails和rspec的新手,在我的rspec测试中发现这个查询时遇到了很多麻烦。这就是我到目前为止所做的:

describe '#completed_code_reviews' do
  let(:trainee_service_client) { LeaderboardsService.new('trainee') }
  let(:start_date) { Date.new(2016, 1, 18) - 1.day }
  let(:end_date) { Date.new(2015, 8, 18) + 2.day }
  let(:order) { 'DESC' }

  let(:person_completed_reviews) { 4 }
  let(:select_result) { double('select') }
  let(:where1_result) { double('where1') }
  let(:joins_result) { double('joins') }
  let(:where2_result) { double('where2') }
  let(:group_result) { double('group') }
  let(:trainees_list) { [] }

  context 'a user has no connections' do
    user_ids = []

    it "returns an empty result" do
        allow(Trainee).to receive(:select)
                .with(:name, :devcenter_start_date, :exit_date, 
                    "count(reviewers.code_review_id) AS reviews_completed"
                ).and_return(select_result)

        allow(select_result).to receive(:where).with(user_id: user_ids).and_return(where1_result)

        allow(where1_result).to receive(:joins).with(:reviewers).and_return(joins_result)

        allow(joins_result).to receive(:where)
                .with(reviewers: { completion_time: start_date..end_date.end_of_day })
                .and_return(where2_result)

        allow(where2_result).to receive(:group).with("trainees.user_id").and_return(group_result)

        allow(group_result).to receive(:order).with(person_completed_reviews: order).and_return(trainees_list)


        expect(trainee_service_client.completed_code_reviews(start_date, end_date)).to eq([])
    end
  end
end

两件事:

1)这实际上没有用。我得到: Failure/Error: expect(trainee_service_client.completed_code_reviews(start_date, end_date, [])).to eq(trainee) Double "group" received :order with unexpected arguments expected: ({:person_completed_reviews=>"DESC"}) got: ("reviews_completed DESC")

如何正确模拟:order方法?

2)此设置似乎也很混乱。有更简洁的方法吗?

1 个答案:

答案 0 :(得分:2)

1)您可以使用以下方法修复错误:

allow(group_result).to receive(:order).with("reviews_completed DESC").and_return(trainees_list)

2)这种嘲弄对我没有意义。你是从哪里得到这个想法的?相反,我会创建你需要的记录。