user3007294
user3007294

Reputation: 951

Test Queries in Rails with MiniTest

Method trying to test:

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"

Current 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

I end up with:

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

I am assuming there is a way more efficent way to test this but have found no luck. Any ideas?

Upvotes: 0

Views: 322

Answers (2)

margo
margo

Reputation: 2927

I think you want to test that the correct comments are returned by the self.by_date method. Does the precise time matter or can it just be within the same day or same hour?

Create another comment and set its created date to yesterday. Then test that the result includes the comment created today and not the comment created yesterday.

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

You'll need to do some additional date manipulation in the method to get comments for the day as opposed to the precise time.

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

If you want the precise time of creation, maybe look at using TimeCop which is helpful for testing on precise timings.

Apologies in advance for minitest syntax errors, I generally use rspec.

Upvotes: 1

Ilya
Ilya

Reputation: 13487

@comment.created_at is a Date, but Comment.by_date(Date.today).first.created_at is a DateTime object.

Try to convert your DateTime object to Date:

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

Upvotes: 1

Related Questions