2016-04-22 66 views
0

方法试图测试:测试查询与MINITEST Rails的

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 

我假设有一种更有效的方法来测试这个,但没有找到运气。有任何想法吗?

回答

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 
+0

啊啊完美!它现在有效。谢谢IIya! – user3007294

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这是在精确的计时测试很有帮助。

为minitest语法错误事先道歉,我通常使用rspec。