0

我刚开始使用 ruby​​ 测试,不知道如何编写测试中的代码。这是来自测试文件的完整任务:

require "temperature"

describe "temperature conversion functions" do
  describe "#ftoc" do
    it "converts freezing temperature" do
      ftoc(32).should == 0
    end

    it "converts boiling temperature" do
      ftoc(212).should == 100
    end

    it "converts body temperature" do
      ftoc(98.6).should == 37
    end

    it "converts arbitrary temperature" do
      ftoc(68).should == 20
    end
  end

  describe "#ctof" do
   it "converts freezing temperature" do
     ctof(0).should == 32
   end

   it "converts boiling temperature" do
     ctof(100).should == 212
   end

   it "converts arbitrary temperature" do
     ctof(20).should == 68
   end
  end
end

在我的代码文件中,我尝试这样做:

def ftoc(f)
  (f - 32) / 1.8
end

并从终端的 rake 命令运行它。比耙子说

temperature conversion functions
#ftoc
converts freezing temperature
converts boiling temperature
converts body temperature (FAILED - 1)
4

1 回答 1

0

我运行这段代码没有任何问题

# controllers/temp_spec.rb
require 'spec_helper'

describe "#ftoc" do
  it "converts freezing temperature" do
    ftoc(32).should == 0
  end
end

def ftoc(f)
  (f - 32) / 1.8
end

# $ rspec spec/controllers/temp_spec.rb
# => One example, 0 failure

我也建议你不要使用==,而是使用eq. 例如ftoc(32).should eq(0)。尽管在这种情况下没有区别。

更新

我刚刚看到你更新的问题。所以你的代码在单独的文件中?Rspec 怎么知道你的代码?如果您的代码不在标准匹配的 Rails 文件中,那就是问题所在。

在您的情况下,您需要在规范中要求代码文件,然后创建类的新实例(如果方法在类中),或者使用模块将方法公开给全局。

于 2013-03-29T16:34:29.397 回答