Alex Harvey
Alex Harvey

Reputation: 15472

Rspec test a method in a simple script

Surely a really easy question for someone, but I can't figure out how to test a method in a simple Ruby script that has methods but no classes.

A very simple method:

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 any classes, and all documentation out there seems to only talk about using Rspec to unit test classes.

So in Rspec, I have presumably will have something 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?

Upvotes: 1

Views: 2242

Answers (1)

Alex Harvey
Alex Harvey

Reputation: 15472

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

Upvotes: 2

Related Questions