[基础]Ruby中使用Rspec 和Rake(非Rails环境)

背景:本文使用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任务


4、spec_helper的内容

Dir.glob(File.join(File.dirname(__FILE__), %w(.. lib *.rb ))).each do |file|
  require file
end
spec_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
end


6、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可以控制程序往前运行。也可以查看变量的值。


猜你喜欢

转载自blog.csdn.net/wendll/article/details/38904655