首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在ruby模块中包含单元测试?

在 Ruby 中,要包含单元测试,您可以使用内置的 Test::Unit 库或者使用更受欢迎的第三方测试框架,如 RSpecMinitest。下面是一个简单的示例,展示了如何在 Ruby 模块中包含单元测试。

首先,确保已安装 RSpecrspec-core gem。在命令行中运行以下命令:

代码语言:bash
复制
gem install rspec
gem install rspec-core

然后,创建一个名为 example_module.rb 的文件,其中包含要测试的模块:

代码语言:ruby
复制
# example_module.rb
module ExampleModule
  def self.add(a, b)
    a + b
  end
end

接下来,创建一个名为 example_module_spec.rb 的文件,其中包含单元测试:

代码语言:ruby
复制
# example_module_spec.rb
require_relative 'example_module'
require 'rspec'

RSpec.describe ExampleModule do
  it 'adds two numbers' do
    expect(ExampleModule.add(2, 3)).to eq(5)
  end

  it 'adds negative numbers' do
    expect(ExampleModule.add(-2, -3)).to eq(-5)
  end

  it 'adds decimal numbers' do
    expect(ExampleModule.add(2.5, 3.5)).to eq(6)
  end
end

现在,在命令行中运行以下命令以执行测试:

代码语言:bash
复制
rspec example_module_spec.rb

如果所有测试都通过,您将在命令行输出中看到类似以下内容的消息:

代码语言:txt
复制
3 examples, 0 failures

这表明您已成功地在 Ruby 模块中包含了单元测试。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券