首页 > 解决方案 > RSpec 测试 - slack bot ruby

问题描述

我是编码新手,我正在尝试对我使用 Ruby 为我的 slack 机器人制作的命令实施 RSpec 测试。该命令使用 .where(Time.zone.now.begining_of_day..Time.zone.now.end_of_day) => 从数据库中检索数据,如下面的代码所示。映射它们中的每一个并将其格式化以供用户输出

代码:

Class StartCommand

  def call
    Answer.where(created_at: Time.zone.now.beginning_of_day..Time.zone.now.end_of_day)
          .map { |answer| "#{answer.slack_identifier}:\n#{answer.body}" }
          .join("\n\n")
  end
end

RSpec 测试:

RSpec.describe RecordCommand do
  describe '#call' do
    it 'retrieves data and format it' do
      StartCommand.new.call
      expect(Answer.where).to eq()
  end
end  

如您所见,我有点迷失如何在 RSpec 测试中实现代码,任何想法、提示或解决方案都会很棒!帮助!我使用 Ruby 和 Ruby on Rails 4

标签: ruby-on-railsrubyrspecrspec-railsslack

解决方案


您可以使用 database-cleaner gem 在测试运行之间擦除数据库。它使您可以根据需要在测试用例中创建记录。每当您测试任何与时间相关的内容时,使用timecop也是一个好主意,因为它会随时冻结您的测试用例并消除Time.now. 假设您已经安装了这些 -

it 'retrieves data and format it' do
  # Freeze time at a point
  base_time = Time.zone.now.beginning_of_day + 5.minutes
  Timecop.freeze(base_time) do
    # setup, create db records
    # 2 in the current day, 1 in the previous day
    Answer.create(slack_identifier: "s1", body: "b1", created_at: base_time)
    Answer.create(slack_identifier: "s2", body: "b2", created_at: base_time + 1.minute)
    Answer.create(slack_identifier: "s3", body: "b3", created_at: base_time - 1.day)
    # call the method and verify the results
    expect(StartCommand.new.call).to eq("s1:\nb1\n\ns2:\nb2")
  end
end

您可能还想orderwhere查询中添加一个。我认为您不能保证 ActiveRecord 每次都以相同的顺序返回记录,除非您指定它(请参阅Rails 3:“MyModel.all”的默认顺序是什么?),并且指定它会使测试更加可靠


推荐阅读