背景:本文使用mac版本,使用rbenv管理ruby版本,文中程序运行在ruby 2.1.0版本
1、本文使用的文件目录结构如下
.
|-- Gemfile
|-- Gemfile.lock
|-- Rakefile
|-- lib
| `-- calculator.rb
`-- spec
|-- calculator_spec.rb
`-- spec_helper.rb
2、Gemfile内容
source 'https://rubygems.org'
gem 'rake'
gem 'rspec'创建Gemfile后通过bundle install可以下载相应rake和rspec的版本。
3、Rakefile的内容
require "rspec/core/rake_task"
task :default => 'spec'
desc "Run all specs"
RSpec::Core::RakeTask.new(:spec) do |t|
t.rspec_opts = "--colour"
t.pattern = "spec/*_spec.rb"
end
这里创建rake任务,这里创建了一个spec的rake任务,且使得default任务指向spec任务
Dir.glob(File.join(File.dirname(__FILE__), %w(.. lib *.rb ))).each do |file|
require file
endspec_helper文件的目的是加载lib中的所有rb文件
5、calculator_spec.rb文件
require 'spec_helper'
describe Calculator do
it "should add two number correctly" do
expect(Calculator.add(1,2)).to be 3
end
end6、calculator.rb文件
class Calculator
class << self
def add(a,b)
a+b
end
def sub(a,b)
a-b
end
end
end创建好所有文件后,在Rakefile文件所在目录,执行rake spec或直接rake,就可以看到测试结果
另附带介绍一个ruby的debug工具byebug
在上述文件的基础上,Gemfile中增加gem 'byebug', '~> 3.2.0'
calculator.rb文件修改为:
require "byebug"
class Calculator
class << self
def add(a,b)
byebug
a+b
end
def sub(a,b)
a-b
end
end
end运行rake spec后就会发现进入命令行调试状态下,按n或s可以控制程序往前运行。也可以查看变量的值。
本文详细介绍如何在Ruby项目中使用RSpec进行单元测试,包括配置Gemfile、Rakefile及spec_helper,配合示例calculator.rb展示了RSpec的具体用法。
&spm=1001.2101.3001.5002&articleId=38904655&d=1&t=3&u=919d53547b6f4ff5b0e542079a9664bd)
193

被折叠的 条评论
为什么被折叠?



