新入手一枚测试工具:rspec

使用rspec测试

rsepec 是一个基于Ruby的测试框架,非常适合TDD开发。Ruby语法非常简单,不只能测试Ruby语言,也可以很方便的测试各种可执行程序,判断输出。
收藏为脚本测试工具。

安装rspec

  1. 安装 ruby: https://rubyinstaller.org/downloads/
  2. 进入命令行,安装rspec
> ruby -v
ruby 3.1.2p20 (2022-04-12 revision 4491bb740a) [x64-mingw-ucrt]

> gem -v
3.3.7

> gem install rspec

测试入门

我们用ruby写个hello world测试用例。

hello.rb

class HelloWorld

   def say_hello 
      "Hello World!"
   end
   
end

describe HelloWorld do 
  it "should say 'Hello World' when we call the say_hello method" do 
	 hw = HelloWorld.new 
	 message = hw.say_hello 
	 expect(message).to eq "Hello World!"
  end
end

测试

> rspec hello.rb
.

Finished in 0.01832 seconds (files took 0.4037 seconds to load)
1 example, 0 failures

我们将测试改错时:

> rspec hello.rb
F

Failures:

  1) HelloWorld should say 'Hello World' when we call the say_hello method
     Failure/Error: expect(message).to eq "Hello World!"

       expected: "Hello World!"
            got: "Hello World"

       (compared using ==)
     # ./hello.rb:13:in `block (2 levels) in <top (required)>'

Finished in 0.05396 seconds (files took 0.40972 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./hello.rb:10 # HelloWorld should say 'Hello World' when we call the say_hello method

上面是用ruby测ruby写的代码,其实可以测任何可执行程序,判断其输出。

测试可执行程序

我们准备一个文件 a.txt

file a:
content is empty

然后写下面的测试程序,读取文件判断内容:

describe "test exe" do 

  def run_script(command)
	 out = nil
	 IO.popen(command) do |pipe|
		out = pipe.readlines
	 end
	 out
  end
  
  it "test type" do 
	result = run_script("type a.txt")
	expect(result).to match_array([
		"file a:",
		"content is empty"
	])
  end
end

当我们测试结果不匹配时,会看到如下错误:

> rspec test-exe.rb
F

Failures:

  1) test exe test type
     Failure/Error:
       expect(result).to match_array([
        "file a:",
        "content is empty"
       ])

       expected collection contained:  ["content is empty", "file a:"]
       actual collection contained:    ["content is empty", "file a:\n"]
       the missing elements were:      ["file a:"]
       the extra elements were:        ["file a:\n"]
     # ./test-exe.rb:14:in `block (2 levels) in <top (required)>'

Finished in 0.07513 seconds (files took 0.4223 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./test-exe.rb:12 # test exe test type

因为 a.txt第一行后面还有个换行符 \n.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值