Я знаю, как решить эту проблему, реализуя сложную сеть условных операторов внутри метода time_string. Тем не менее, я пытаюсь использовать мои новые знания метода Symbol # to_proc. Как вы можете видеть, я построил метод «padded», и я пытаюсь назвать его с помощью синтаксиса '&', но я продолжаю получать это сообщение об ошибке. Я пробовал несколько разных форматов, но безрезультатно.Тест First Ruby - Timer: проблемы с внедрением символа # to_proc в методе time_string
я получаю это же сообщение об ошибке:
"Undefined method 'seconds=' for nil:NilClass"
Мой Таймера определение класса от timer.rb:
class Timer
attr_accessor :seconds
def initialize
@seconds = 0
end
def padded n
"#{n}".rjust(2, '0')
end
def time_string
t_hours = @seconds/3600
t_mins = (@seconds % 3600)/60
t_seconds = @seconds % 60
@time_string = [t_hours, t_mins, t_seconds].map(&:padded).join(":")
end
end
The Rspec код из timer_spec.rb:
# # Topics
#
# * classes
# * instance variables
# * string formats
# * modular arithmetic
#
# # Timer
require '09_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
it "pads zero" do
expect(@timer.padded(0)).to eq("00")
end
it "pads one" do
expect(@timer.padded(1)).to eq("01")
end
it "doesn't pad a two-digit number" do
expect(@timer.padded(12)).to eq("12")
end
describe "time_string" do
before(:each) do
@timer = Timer.new
end
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
end
Сообщение об ошибке с моего терминала:
MacBook-Air:test1 ***$ bundle exec rspec spec/09_timer_spec.rb
Timer
should initialize to 0 seconds
pads zero
pads one
doesn't pad a two-digit number
time_string
should display 0 seconds as 00:00:00 (FAILED - 1)
Failures:
1) Timer time_string should display 0 seconds as 00:00:00
Failure/Error: expect(@timer.time_string).to eq("00:00:00")
NoMethodError:
undefined method `padded' for 0:Fixnum
в вашем случае вам не нужно, чтобы добавить методы «DEF секунд = (время) "и" def seconds "вручную. Когда вы пишете attr_accessor: секунды ruby сделают это за вас – sig
Исправьте отступ от вашей спецификации, и ошибка станет очевидной. – Stefan
Только что отредактировал спецификацию, переместил «конец» в нижнюю часть, чтобы включить описание «time_string» в область описания «Таймер». Теперь я получаю это .... Ошибка/Ошибка: ожидать (@ timer.time_string) .to eq («00:00:00») NoMethodError: undefined method 'padded 'for 0: Fixnum – Sedulity