耙 rspec 测试不运行



我按照 rspec 页面中的介绍进行操作,然后在我的 rakefile 中添加了一个测试任务来进行简单的文件读取测试:

#Rakefile
task default: %w[test]
task :test do
  ruby "spec/file_reader_spec.rb"
end
#spec/file_reader_spec.rb
require './lib/filereader'
require 'rspec'
RSpec.describe "file_reader" do
    context "with sample test input file" do
        it "reads a file and prints its contents" do
            @file_reader = FileReader.new
            expect(@file_reader.input_file('./files/test_input.txt')).to eq ('file text')
        end
    end
end

但是当我运行 rake 命令时,它什么也没输出,只有一行显示 spec 文件已执行:

$rake
/Users/mrisoli/.rvm/rubies/ruby-2.1.1/bin/ruby spec/file_reader_spec.rb

为什么它没有输出所描述的测试?

您正在使用 ruby 而不是 rspec 运行规范。这就是为什么你看不到任何输出,你的测试将像一个普通的 ruby 脚本一样运行。

Rakefile更改为运行rspec

begin
  require 'rspec/core/rake_task'
  RSpec::Core::RakeTask.new(:spec)
  task :default => :spec
rescue LoadError
  puts "RSpec is not installed!"
end

更多细节在这里。

更新

如果要将参数传递给 rspec,可以这样做:

RSpec::Core::RakeTask.new(:spec) do |t|
  t.rspec_opts = "--format documentation"
end

这将以格式作为文档运行规范。


题外话

在描述类时,最佳做法是应将类传递给describe方法而不是字符串。这样你的代码看起来更干净,rspec 将负责自己实例化它(实例将作为subject提供)。

例如:

RSpec.describe FileReader do
  context "with sample test input file" do
    it "reads a file and prints its contents" do
        expect(subject.input_file('./files/test_input.txt')).to eq ('file text')
    end
  end
end

最新更新