rspec:尝试模拟1.month-before时无法定义单例错误

时间:2017-11-13 19:11:09

标签: ruby-on-rails unit-testing rspec mocking

我正在尝试测试以下方法:

  def update_players_data(team_id, import_id)
    team = Team.find(team_id)
    players_to_update = team.players.where("updated_at < ?", 1.month.ago)
    players_to_update.each { |player| update_player(player, import_id) }
  end

使用此测试类:

  context "update_players_data" do
    let(:player1) { double(:player) }
    let(:player2) { double(:player) }
    let(:players) { [player1, player2]}
    let(:players_to_update) { [player1] }
    let(:date) { 1.month.ago }
    let(:import_id) { "import_id" }
    let(:team_id) { "team_id" }
    let(:team) { double(:team) }

    before do
      allow(Team).to receive(:find).with(team_id) { team }
      allow(team).to receive(:players) { players }
      allow(1).to receive_message_chain(:month, :ago) { date }
      allow(players).to receive(:where).with("geocoded_at < ?", date) { players_to_update }
    end

    it "calls update_player" do
      subject.update_players_data(team_id, import_id)
      expect(subject).to have_received(:update_player).with(player1, import_id)
    end
  end

但是当试图在这里模拟日期时,测试会中断:

allow(1).to receive_message_chain(:month, :ago) { date }

抛出'TypeError:无法定义单例'

问题是我不能在测试中调用1.month.ago,因为测试日期与执行时间的日期相差几毫秒导致测试失败。日期必须被嘲笑。但我找不到正确的方法。

1 个答案:

答案 0 :(得分:1)

使用类似Timecop的内容。

此外

    team.players.where("updated_at < ?", 1.month.ago).update_all(import_id: import_id)

可以

@media only screen 
and (*Your threshold criteria goes here* EXAMPLE:  max-width : 1000px) {   
  //css goes here with whatever css you want to fire at this threshold
}

(假设您只是更新该函数中的值)。