ruby-on-rails - 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
解决方案
您可以使用 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
您可能还想order
在where
查询中添加一个。我认为您不能保证 ActiveRecord 每次都以相同的顺序返回记录,除非您指定它(请参阅Rails 3:“MyModel.all”的默认顺序是什么?),并且指定它会使测试更加可靠
推荐阅读
- excel - Excel VBA 不会关闭最终工作簿
- html - HTML 元素不重叠
- javascript - 如何使用@coreui-react 每次只折叠一个?
- python - 使用字典检查列表中的字谜
- javascript - 如何在每个测试中以不同方式模拟用户模块?
- r - 修改后的 cumsum - 以比率 r 汇总
- php - ErrorException:间接修改重载属性 App\Answer::$attribute 无效
- java - 使用 SimpleDateFormat 格式化日期时抛出 ClassCastException
- c# - 从android java返回字节数组引用到csharp unity
- json - 如何从嵌套的json中提取键值对