0

I'm new at coding and I'm trying to implement RSpec testing to a command I made for my slack bot using Ruby. The command retrieves the data from the database using .where(Time.zone.now.begining_of_day..Time.zone.now.end_of_day) => showed in the code down bellow. map through each of them and format it for the user output

Code:

Class StartCommand

  def call
    Answer.where(created_at: Time.zone.now.beginning_of_day..Time.zone.now.end_of_day)
          .map { |answer| "#{answer.slack_identifier}:\n#{answer.body}" }
          .join("\n\n")
  end
end

RSpec testing:

RSpec.describe RecordCommand do
  describe '#call' do
    it 'retrieves data and format it' do
      StartCommand.new.call
      expect(Answer.where).to eq()
  end
end  

As you can see I'm kinda lost how to implement the code in the RSpec testing, any ideas, hints or solutions would be awesome! Help! Im using Ruby and Ruby on Rails 4

Adil B
  • 14,635
  • 11
  • 60
  • 78
Noname
  • 91
  • 3
  • 11

1 Answers1

1

You can use the database-cleaner gem to wipe the DB between test runs. It lets you can create records in your test case as needed. It's also a good idea to use the timecop whenever you are testing anything time-related, since it freezes your test case at any time and removes the unpredictability of Time.now. Assuming you have installed those -

it 'retrieves data and format it' do
  # Freeze time at a point
  base_time = Time.zone.now.beginning_of_day + 5.minutes
  Timecop.freeze(base_time) do
    # setup, create db records
    # 2 in the current day, 1 in the previous day
    Answer.create(slack_identifier: "s1", body: "b1", created_at: base_time)
    Answer.create(slack_identifier: "s2", body: "b2", created_at: base_time + 1.minute)
    Answer.create(slack_identifier: "s3", body: "b3", created_at: base_time - 1.day)
    # call the method and verify the results
    expect(StartCommand.new.call).to eq("s1:\nb1\n\ns2:\nb2")
  end
end

You may also want to add an order to your where query. I don't think you can guarantee that ActiveRecord returns records in the same order each time unless you specify it (see Rails 3: What is the default order of "MyModel.all"?), and specifying it would make the test more dependable

max pleaner
  • 26,189
  • 9
  • 66
  • 118