我有RSpec问题。根据那个问题,我在ruby中写了一个解决方案。但是当使用RSpec运行我期望得到一个值时,我得到nil
这里是RSpec
require 'timer'
describe "Timer" do
before(:each) do
@timer = Timer.new
end
it "should initialize to 0 seconds" do
expect(@timer.seconds).to eq(0)
end
describe 'time_string' do
it "should display 0 seconds as 00:00:00" do
@timer.seconds = 0
expect(@timer.time_string).to eq("00:00:00")
end
it "should display 12 seconds as 00:00:12" do
@timer.seconds = 12
expect(@timer.time_string).to eq("00:00:12")
end
it "should display 66 seconds as 00:01:06" do
@timer.seconds = 66
expect(@timer.time_string).to eq("00:01:06")
end
it "should display 4000 seconds as 01:06:40" do
@timer.seconds = 4000
expect(@timer.time_string).to eq("01:06:40")
end
end
这是我写的解决方案:
class Timer
attr_accessor :seconds, :time_string
def seconds=(num)
@seconds=num
end #seconds
def time_string
s=@seconds%60
m=@seconds/60
h=m/60
m=m%60
@time_string="%02d:%02d:%02d" %[h,m,s]
end #time_string
end #class
我收到错误
Failure/Error: expect(@timer.seconds).to eq(0)
expected: 0
got: nil
答案 0 :(得分:3)
那是因为你在没有任何参数的情况下初始化Timer.new
。因此,seconds
为nil
您需要:
before(:each) do
@timer = Timer.new
@timer.seconds = 0
end
或实现初始化程序:
class Timer
attr_accessor :seconds, :time_string
def initialize
@seconds = 0
end
...