新入手一枚测试工具:rspec

Posted 悟初境

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了新入手一枚测试工具: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.

以上是关于新入手一枚测试工具:rspec的主要内容,如果未能解决你的问题,请参考以下文章

Rails, Restful Authentication & RSpec - 如何测试需要身份验证的新模型

如何使用rspec编写测试用例来发送通知消息

设置 RSpec 以测试 gem(不是 Rails)

如何使用 rspec 测试 mandrill api

使用Rails Rspec进行测试 - 预期和得到的不匹配

如何设置RSpec以最后测试功能,并且仅在所有其他测试通过时