自定义格式化程序
RSpec 附带通用输出格式化程序。你可以使用 --format
命令行选项 告诉 RSpec 使用哪个格式化程序。
但是,当 RSpec 的内置输出格式化程序无法满足你的所有需求时,你可以编写自己的自定义格式化程序并告诉 RSpec 使用该格式化程序。最简单的方法是继承 RSpec 的 BaseTextFormatter
,然后仅覆盖你想要修改的方法。
自定义格式化程序
给定名为“custom_formatter.rb”的文件,其中包含
class CustomFormatter
# This registers the notifications this formatter supports, and tells
# us that this was written against the RSpec 3.x formatter API.
RSpec::Core::Formatters.register self, :example_started
def initialize(output)
@output = output
end
def example_started(notification)
@output << "example: " << notification.example.description
end
end
以及名为“example_spec.rb”的文件,其中包含
RSpec.describe "my group" do
specify "my example" do
end
end
当我运行 rspec example_spec.rb --require ./custom_formatter.rb --format CustomFormatter
则输出应包含“example: my example”
以及退出状态应为 0。