Alex Harvey Alex Harvey - 7 months ago 12
Ruby Question

Rspec test a function in a simple script

Surely a really easy question for someone, but I can't figure out how to test a simple function in a Ruby script.

A very simple function:

def s2hm(s)
"%sh %sm" % [s / 3600, s / 60 % 60].map { |t| t.to_s }
end


Since it's just a simple script, I don't have a class, and all documentation out there seems to only talk about unit testing classes.

So in Rspec I have something presumably like:

describe '#s2hm' do
it 'should convert seconds to hours and minutes' do
... # what goes here
end
end


Could someone advise on how I'd complete that describe block? Many thanks.

Answer

For anyone else struggling with something like this, I got it to work using:

describe '#s2hm' do
  it 'should convert seconds to hours and minutes' do
    expect(s2hm(7320)).to eq '2h 2m'
  end

  it 'should convert seconds to hours and minutes' do
    expect(s2hm(7200)).to eq '2h 0m'
  end

  it 'should convert seconds to hours and minutes' do
    expect(s2hm(12345678)).to eq '3429h 21m'
  end
end