Reputation: 721
I am using Rails 5.2.2.1 and Rspec. Please, how can I stub time to always have this test green?
Few edit I added Timecop as suggested and updated my question but it is still failing
Today my test fails because it's the first day of the month...
before(:each) do
Timecop.freeze(Time.local(2019, 03, 31, 12, 0, 0))
end
let(:date_from) { Timecop.freeze(Time.local(2019, 03, 26, 12, 0, 0)) }
let(:date_to) { Timecop.freeze(Time.local(2019, 03, 31, 12, 0, 0)) }
subject { Dashboard.new(date_from: @date_from, date_to: @date_to) }
describe "#sales_by_week" do
it "returns the number of sales by week" do
create(:sale, created_at: 2.weeks.ago)
create(:sale, created_at: 3.days.ago)
create(:sale, created_at: Date.today )
res = subject.sales_by_week
expect(res.values.last).to eq(2)
end
end
describe "#sales_by_month" do
it "returns the number of sales by month" do
create(:sale, created_at: 2.day.ago)
create(:sale, created_at: 1.day.ago)
res = subject.sales_by_month
expect(res.values.last).to eq(2)
end
end
Here are the method I am testing:
class Dashboard
attr_reader :date_from, :date_to
def initialize(params)
params ||= {}
@date_from = parsed_date(params[:date_from],Time.now.beginning_of_month.to_date.to_s)
@date_to = parsed_date(params[:date_to], (Date.today + 1).to_s)
end
def sales_by_week
Sale.group_by_week(:created_at, range: (@date_from..@date_to),time_zone: "Paris", week_start: :mon).count
end
def sales_by_month
Sale.group_by_month(:created_at, range: (@date_from..@date_to),time_zone: "Paris", week_start: :mon).count
end
end
Upvotes: 0
Views: 1247
Reputation: 4440
You can use Timecop:
It provides very simple way to freeze
time at any point you want, for example:
describe "#sales_by_week" do
before { Timecop.freeze(Time.now.beginning_of_week+6.days) }
it "returns the number of sale by week" do
create(:sale, created_at: 2.weeks.ago)
create(:sale, created_at: 3.days.ago)
create(:sale, created_at: Date.today )
res = subject.sales_by_week
expect(res.values.last).to eq(2)
end
end
Upvotes: 2