使用MiniTest在Rails中测试查询

时间:2016-04-22 20:51:20

标签: ruby-on-rails minitest

尝试测试的方法:

def self.by_date(date)
  where("DATE(created_at) = ?", date)
end

Comments.yml(fixture):

one:
  user_id: 1
  job_id: 24
  content: "This is a test"

当前测试:

require 'test_helper'
require 'date'

class CommentTest < ActiveSupport::TestCase

setup do
  @comment = comments(:one)
end

test 'organizes by date' do
  @comment.created_at = Date.today
  assert_equal @comment.created_at, Comment.by_date(Date.today).first.created_at
end

end

我最终得到了:

2) Failure:
  CommentTest#test_organizes_by_date 
  --- expected
  +++ actual
  @@ -1 +1 @@
 -Fri, 22 Apr 2016 00:00:00 UTC +00:00
 +Fri, 22 Apr 2016 20:48:42 UTC +00:00

我假设有一种方法可以更有效地测试,但没有找到运气。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

@comment.created_atDate,但Comment.by_date(Date.today).first.created_atDateTime对象。

尝试将DateTime对象转换为Date

assert_equal @comment.created_at, Comment.by_date(Date.today).first.created_at.to_date

答案 1 :(得分:1)

我认为您要测试self.by_date方法返回的正确注释。准确的时间是重要还是只能在同一天或同一小时内?

创建另一条评论并将其创建日期设置为昨天。然后测试结果是否包含今天创建的评论,而不是昨天创建的评论。

class CommentTest < ActiveSupport::TestCase

  setup do
    @comment1 = comments(:one)
    @comment2 = comments(:one)
  end

  test 'organizes by date' do
    @comment1.created_at = Time.now
    @comment2.created_at = Time.now - 1.day
    assert_equal [@comment1], Comment.by_date(Time.now)
    assert_equal [@comment2], Comment.by_date(Time.now - 1.day)
  end

end

您需要在方法中进行一些额外的日期操作,以获取当天的评论而不是准确的时间。

def self.by_date
  where(created_at: Time.now.day)
end

如果您想要精确的创作时间,可以查看使用TimeCop,这有助于测试精确的时间。

预先为最小的语法错误道歉,我通常使用rspec。