【问题标题】:Issue with Rspec Timer testRspec 计时器测试问题
【发布时间】:2013-07-07 05:38:43
【问题描述】:

我被困在二档,请检查我的代码并给我一些意见。谢谢。

class Timer
    def initialize(seconds = 0,time_string = "00:00:00")
        @seconds = seconds
        @time_string = time_string

    end

    def seconds=(new_sec)
        @seconds = new_sec
    end

    def seconds
        @seconds
    end

    def time_string=(new_time)

        hh = seconds/3600
        mm = seconds%3600/60
        ss = seconds%60
        new_time = "#{hh}:#{mm}:#{ss}" 
        @time_string = new_time 
    end

    def time_string
        @time_string
    end
end

Rspec:

require 'timer'

describe "Timer" do
  before(:each) do
    @timer = Timer.new
  end

  it "should initialize to 0 seconds" do
    @timer.seconds.should == 0
  end

  describe 'time_string' do
    it "should display 0 seconds as 00:00:00" do
    @timer.seconds = 0
    @timer.time_string.should == "00:00:00"
  end

  it "should display 12 seconds as 00:00:12" do

    @timer.seconds = 12
    @timer.time_string.should == "00:00:12"
  end

  it "should display 66 seconds as 00:01:06" do
    @timer.seconds = 66
    @timer.time_string.should == "00:01:06"
  end

  it "should display 4000 seconds as 01:06:40" do
    @timer.seconds = 4000
    @timer.time_string.should == "01:06:40"
  end
end

【问题讨论】:

  • 这在codereview.stackexchange.com 上可能会更好(假设代码有效)。要在 Stack Overflow 上回答这个问题,请描述您遇到的具体问题。
  • 作为一个快速提示,但是为了匹配测试行为,您不应该设置或存储@time_string,只需按需计算即可。
  • 这是什么课程?很多人问同样的问题

标签: ruby class time rspec numbers


【解决方案1】:

下面是一个赋值def time_string=(new_time),但你实际上并没有使用 new_time 来改变任何东西的值,所以最好说def time_string 只定义一个getter。 (您的测试并未表明您希望能够通过提供的 time_string 设置时间。)

正如 Neil Slater 指出的那样,您不需要实例变量 @time_string,只需从 time_string 方法返回 new_time,您就拥有了您想要的。所以你的代码...

def time_string=(new_time)

        hh = seconds/3600
        mm = seconds%3600/60
        ss = seconds%60
        new_time = "#{hh}:#{mm}:#{ss}" 
        @time_string = new_time 
    end

替换为

def time_string
  hh = @seconds/3600
  mm = @seconds%3600/60
  ss = @seconds%60
  new_time = "#{hh}:#{mm}:#{ss}" 
end

【讨论】:

  • 知道了。谢谢。我的解决方案是将 new_time 替换为: new_time = [hh,mm,ss].map { |e| e.to_s.rjust(2,'0') }.join ':'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-01
  • 2015-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多