如何使用Ruby测试?

时间:2013-03-29 15:53:38

标签: ruby rspec tdd

我刚刚开始使用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)

1 个答案:

答案 0 :(得分: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文件中,那就是问题所在。

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