Reputation: 3550
I have a method in my Event model:
def when
self.starts_at.strftime("%a %b %e @ %-I:%M")
end
which outputs correctly in the rails console or on a webpage.
However, doing an rspec test like this:
it "has simple date display" do
game = FactoryGirl.build(:event, starts_at: DateTime.parse("1/1/2014 3:30pm"))
game.when.should == "Wed Jan 1 @ 3:30"
end
fails, because of:
1) Event has simple date display
Failure/Error: event.when.should == "Wed Jan 1 @ 3:30"
expected: "Wed Jan 1 @ 3:30"
got: "Wed Jan 1 @ 3:30" (using ==)
Why is there a random space in my formatted DateTime? Shouldn't the same DateTime code be loaded/running for tests and console?
Upvotes: 1
Views: 564
Reputation: 38645
The reason your test is failing is because the %e
directives in strftime
is:
%e - Day of the month, blank-padded ( 1..31)
So the statement DateTime.parse("1/1/2014 3:30pm").strftime("%a %b %e @ %-I:%M")
yields Wed Jan 1 @ 3:30
(with extra space prepended for days between 1 through 9).
You could use %d
directive instead which gives day of month, zero-padded. E.g.
# Event model
def when
self.starts_at.strftime("%a %b %d @ %-I:%M")
end
Then in your spec:
it "has simple date display" do
game = FactoryGirl.build(:event, starts_at: DateTime.parse("1/1/2014 3:30pm"))
game.when.should == "Wed Jan 01 @ 3:30"
end
Upvotes: 2
Reputation: 27789
You're using the %e
format directive, which is for the blank-padded day of month. It sounds like you want the unpadded day of the month directive, which is %-d
. Here are the docs.
Upvotes: 3