PaperKraftMike
PaperKraftMike

Reputation: 99

RSPEC test and Ruby Object

So I'm trying to write some code to make an RSPEC test pass for Ruby. But I'm having some trouble even getting the first test to pass. I think if I can have a little help with this, I'll be able to get the rest. But I can post the rest of the tests if that makes it easier to offer advice.

So it's constructing a fahrenheit/celsius converter, but using objects and classes instead of just defining a couple of methods to do the conversions.

The first part looks like this

   require "temperature"

describe Temperature do

  describe "can be constructed with an options hash" do
    describe "in degrees fahrenheit" do
      it "at 50 degrees" do
        Temperature.new(:f => 50).in_fahrenheit.should == 50
      end

One of the hints in the instructions says that the Temperature object constructer should accept an options hash with either a :celsius or :fahrenheit entry.

Any help or hints would be greatly appreciated. I've been stuck on this test for the last few weeks. Thanks in advance.

Upvotes: 0

Views: 952

Answers (1)

LazyMonkey
LazyMonkey

Reputation: 527

I think your Temperature class needs some work. Why not have a 'scale' attribute that can set the base value of your Temperature object?

Here's a modified version of what you've posted:

class Temperature
  attr_accessor :value, :scale
  def initialize(value, options={})
    @value = value
    if options.has_key?(:scale)
      @scale = options[:scale]
    else
      @scale = :c
    end
  end
  def in_fahrenheit()
    if @scale == :c
      ( @value * 9.0/5.0 ) + 32.0 
    else
      @value
    end
  end 
end

There's no need to create a new Temperature object when you call #in_fahrenheit. You can make your current object convert a number (stored in an attribute) into fahrenheit. You can add the temperature information when you create your object:

t1=Temperature.new(68, :scale =>:f)
t2=Temperature.new(0)

2.0.0dev :199 > t1.in_fahrenheit  => 68 
2.0.0dev :200 > t2.in_fahrenheit  => 32.0 

Upvotes: 1

Related Questions