0

I'm struggling with using RSpec with conditional statements. What is an example of a spec file for the following lines of code? The drive method is what I am trying to break down into a spec file. I'm not sure how to go about the conditional statements.

class Car

def initialize
  @fuel = 10
  @distance = 0 
end

def drive(miles)
  if (@fuel -= miles/20) >= 0
    @distance += miles
    @fuel -= miles/20
else 
    @distance += @fuel * 20 
    @fuel = 0 
    puts "You're out of gas!"
end
end

def fuel_up
  gallons_needed = 10 - @fuel
  puts "The amount of gallons needed will cost you $#{3.5 * gallons_needed}"
end

def to_s
  puts "I'm a car. I've driven #{@distance} miles and have #{@fuel} gallons of gas left."
end

end

car_a = Car.new
car_b = Car.new
car_a.drive(10)
car_a.to_s
car_b.drive(133)
car_b.to_s
car_b.fuel_up
car_a.fuel_up
car_a.drive(500)
2
  • 1
    10/20 is 0. Are you aware of that? Commented Oct 6, 2014 at 15:28
  • sawa - yes I'm aware of that! It was in our instructions to do it that way, although I'm not sure if that is correct. Commented Oct 6, 2014 at 18:09

1 Answer 1

2

We need info on how @distance and @fuel are calculated and/or initialized.

As an example, based on what I can tell about your code:

require 'rspec'

describe Car do
  it '#drive' do
    car = Car.new
    car.drive(10)

    expect(car.distance).to eq 10
    expect(car.fuel).to eq 0.5
  end

end

From a testing standpoint, you give your function a number and your function does some stuff to some other variables. That's what you should test for, specifically what the expectation of those calculations are.

Sign up to request clarification or add additional context in comments.

3 Comments

@sawa yep you're right, but maybe my test will bring that to light for him/her.
Thank you all for your response. I added the rest of the code so you can get a better picture. I understand your spec above, but do I need to write out any of the @fuel -= distance, etc in the spec, or just what the method should be expecting to do .. i.e. expect(car.distance).to eq 10?
You're not testing that the -= operator is doing it's job, you're testing that your function given X, does Y & Z. You could rewrite my test for all the permutations and expect the results necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.