关于rspec中Ruby类Timer的问题

时间:2013-07-03 18:54:54

标签: ruby class rspec timer format

我是一个Ruby新手试图使用以下Rspec创建一个类Timer:

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

但是我不理解Rspec的返回错误消息,该消息表示" Timer应该初始化为0秒"我在开始时遇到了我的代码而且非常感谢任何人谁可以解释下面我的代码有什么问题。感谢。

class Timer
    def intialize(seconds)
        @seconds = seconds
    end
    def seconds=(new_seconds = 0)
        @seconds = new_seconds
    end
    def seconds
        @seconds
    end
end

3 个答案:

答案 0 :(得分:2)

我认为您的initialize方法应该使用可选参数:

class Timer
  def initialize(seconds = 0)
    @seconds = seconds
  end
  def seconds=(new_seconds)
    @seconds = new_seconds
  end
end

答案 1 :(得分:1)

Stefan的答案很好,但我使用了以下代码,它可以完美地解决您正在处理的其他问题。

class Timer
  attr_accessor :seconds

  def initialize
    @seconds = 0
  end
end

attr_accessor创建实例变量@seconds,并将其初始化为0。 虽然我不能赞同这个答案。我在这个stackoverflow页面上找到了它及其非常详尽的解释:What is attr_accessor in Ruby?

谢谢你hakunin。

答案 2 :(得分:0)

试图以最“懒惰”的方式解决这个问题。测试工作正常,但我认为必须有简短而优化的方法来解决它。

class Timer
      attr_accessor  :seconds
  def initialize seconds=0
      @seconds = seconds
  end
  def time_string
      res=[]
      tt=@seconds.div(3600)
      if tt<10
         tt = '0' + tt.to_s
      end
      res.push(tt)
      tt=(@seconds-@seconds.div(3600)*3600).div(60)
      if tt<10
         tt = '0' + tt.to_s
      end
         res.push(tt)
         tt=@seconds-@seconds.div(3600)*3600-((@seconds-@seconds.div(3600)*3600).div(60))*60
      if tt<10
         tt = '0' + tt.to_s
      end
  res.push(tt)
  res.join(':')
  end
end