【问题标题】:RSPEC test and Ruby ObjectRSPEC 测试和 Ruby 对象
【发布时间】:2013-03-01 15:49:48
【问题描述】:

所以我正在尝试编写一些代码来使 Ruby 的 RSPEC 测试通过。但是我什至无法通过第一个测试。我想如果我能在这方面得到一点帮助,我就能得到剩下的。但如果这样更容易提供建议,我可以发布其余的测试。

所以它构建了一个华氏/摄氏度转换器,但使用对象和类而不是仅仅定义几个方法来进行转换。

第一部分是这样的

   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

说明中的一个提示是,Temperature 对象构造器应该接受带有 :celsius 或 :fahrenheit 条目的选项散列。

任何帮助或提示将不胜感激。在过去的几周里,我一直被困在这个测试中。提前致谢。

【问题讨论】:

  • 这是我迄今为止试图通过的第一个测试。 class Temperature attr_accessor :fahrenheit def initialize options = {} @fahrenheit = :f end def in_fahrenheit({ :f}) Temperature.new({:f}) end end
  • 您的代码 sn-p 不完整。请添加缺少的“结束”关键字。

标签: ruby rspec


【解决方案1】:

我认为您的温度课程需要一些工作。为什么没有一个可以设置温度对象基础值的“刻度”属性?

这是您发布的内容的修改版本:

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

调用#in_fahrenheit 时无需创建新的温度对象。您可以使当前对象将数字(存储在属性中)转换为华氏温度。您可以在创建对象时添加温度信息:

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 

【讨论】:

  • 谢谢@LazyMonkey,我知道你在做什么。我很欣赏这些提示,但是当我尝试运行它时,我得到了通过测试: undefined method *' for {:f=>50}:Hash # ./08_temperature_object/temperature.rb:13:in in_fahrenheit' # ./08_temperature_object/temperature_object_spec.rb:27 知道是什么原因造成的吗?
  • 不清楚你指的是你原来的课程还是我的模组。我猜您的 RSpec 测试与您的 #in_fahrenheit 方法有问题,因为您将 {:f} 定义为方法参数。看起来不对(它只是大括号内的符号,而不是 :key => 值对。)不确定这是有效的 Ruby 语法(我无法通过!)请发布并格式化您的温度类。
猜你喜欢
  • 1970-01-01
  • 2016-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多