简体   繁体   English

使用RSpec时Rails DateTime中的随机空间?

[英]Random space in Rails DateTime when using RSpec?

I have a method in my Event model: 我的Event模型中有一个方法:

  def when
    self.starts_at.strftime("%a %b %e @ %-I:%M")
  end

which outputs correctly in the rails console or on a webpage. 在rails控制台或网页上正确输出。

However, doing an rspec test like this: 但是,像这样进行rspec测试:

  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? 为什么我的格式化DateTime中有一个随机空间? Shouldn't the same DateTime code be loaded/running for tests and console? 是否应该为测试和控制台加载/运行相同的DateTime代码?

You're using the %e format directive, which is for the blank-padded day of month. 您正在使用%e格式指令,该指令适用于每月填空的日期。 It sounds like you want the unpadded day of the month directive, which is %-d . 听起来你想要月份指令的未填充日期,即%-d Here are the docs . 这是文档

The reason your test is failing is because the %e directives in strftime is: 测试失败的原因是因为strftime%e指令是:

%e - Day of the month, blank-padded ( 1..31) %e - 每月的日期,空白填充(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). 所以语句DateTime.parse("1/1/2014 3:30pm").strftime("%a %b %e @ %-I:%M") Wed Jan 1 @ 3:30 DateTime.parse("1/1/2014 3:30pm").strftime("%a %b %e @ %-I:%M")产生Wed Jan 1 @ 3:30 (前面有额外的空格)在1到9之间的几天。

You could use %d directive instead which gives day of month, zero-padded. 您可以使用%d指令代替,该指令给出了月填充,零填充。 Eg 例如

# 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM