在RSpec / Rails验收测试中,有没有办法将消息推送到RSpec输出并保持良好的缩进?

我的验收测试(RSpec / Capybara)有一些很长的步骤序列都在一个单独的it...do块下,我想手动将每个步骤的一些附加文档添加到RSpec文档输出中。

那么RSpec输出(文档格式)目前是这样的:

 FooController New user creates account and creates profile it passes 

在很长的步骤序列中,我想将一些额外的信息推送到输出:

 FooController New user creates account and creates profile ... new user saw signup page! ... new user got email confirmation! ... confirmation link worked! ... new user saw empty profile! ... new user filled in profile it passes 

在记录应用程序方面,这些额外的陈述将比具有单个“传递”结果消息的大黑盒子更好。

由于显然没有办法使用多个it...do块来构建validation测试的长序列步骤,我希望有一种简单的方法可以将其他消息推送到RSpec输出流,理想情况是它们是缩进并显示(红色/绿色),就好像它们被拍或分开it...do例子。

这就是我所做的…在我的规范中添加了一个nextstep(“message”)方法,使用awesome_print gem将“消息”输出到控制台,这样我就可以对它进行着色,也可以对记录器进行着色。

  def nextstep(txt) $step += 1 @speclog.debug '' @speclog.debug '' @speclog.debug "#{$scene}, step: #{$step}: " + txt ap (' ' * ($indent * 2 - 1)) + "step: #{$step}: " + txt, {:color => {:string => :blueish}} end 

有点hackish,但它确实给我们运行rspec时非常好的描述性输出,例如,如果我们有

 it "New user creates account and creates profile" do # some assertions nextstep "... new user saw signup page!" # some assertions nextstep " ... new user got email confirmation!" # some assertions nextstep " ... confirmation link worked!" # some assertions nextstep "... new user saw empty profile!" # some assertions nextstep "... new user filled in profile" end 

如问题所示,我们得到更具描述性的规范输出(如果失败,我们会看到我们所处的步骤):

  step 1: ... new user saw signup page! step 2: ... new user got email confirmation! step 3: ... confirmation link worked! step 4: ... new user saw empty profile! step 5: ... new user filled in profile" 

最后,我通过在spec/support文件夹中的某处包含以下代码来选择自定义DocumentationFormatter (以确保自动加载):

 require "rspec/core/formatters/documentation_formatter" class RSpec::Core::ExampleGroup def step(msg) example.metadata[:step_messages] << msg if example.metadata[:step_messages] yield end end class RSpec::Core::Formatters::DocumentationFormatter def example_started(example) example.metadata[:step_messages] = [] end def example_passed(example) output.puts passed_output(example) print_steps(example) end private def print_steps(example) example.metadata[:step_messages].each do |msg| output.puts detail_color("#{' ' * (@group_level + 1)}#{msg}") end end end 

通过这个技巧,您可以获得一个可以在it块中使用的step方法。 使用--format documentation运行rspec时,将打印出来自step块的相关消息,并适当缩进。 例如,以下代码

 it "should show all and only appoved posts" do step "show all approved posts" do Post.all.approved.each do |post| should have_content(post.title) end end step "show only approved posts" do should have_selector(".post", count: Post.all.approved.count) end end 

将产生以下输出(步骤字符串以浅蓝色着色):

 should show all and only appoved posts show all approved posts show only approved posts 

这无疑是一个非常粗略的解决方案,但它可能会通过更多的工作变得更好。