使用 MiniTest 在 Rails 中测试查询
Test Queries in Rails with MiniTest
尝试测试的方法:
def self.by_date(date)
where("DATE(created_at) = ?", date)
end
Comments.yml(夹具):
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
我假设有一种更有效的方法来测试它,但没有找到运气。有什么想法吗?
@comment.created_at
是一个 Date
,但 Comment.by_date(Date.today).first.created_at
是一个 DateTime
对象。
尝试将您的 DateTime
对象转换为 Date
:
assert_equal @comment.created_at, Comment.by_date(Date.today).first.created_at.to_date
我认为您想测试 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。
尝试测试的方法:
def self.by_date(date)
where("DATE(created_at) = ?", date)
end
Comments.yml(夹具):
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
我假设有一种更有效的方法来测试它,但没有找到运气。有什么想法吗?
@comment.created_at
是一个 Date
,但 Comment.by_date(Date.today).first.created_at
是一个 DateTime
对象。
尝试将您的 DateTime
对象转换为 Date
:
assert_equal @comment.created_at, Comment.by_date(Date.today).first.created_at.to_date
我认为您想测试 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。