2016-04-22 62 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。