在 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块来构建验收测试的长步骤序列,我希望有一种简单的方法可以将其他消息推送到 RSpec 输出流,理想情况下将它们缩进并显示(红色/绿色)就像它们是拍拍或单独的it...do示例一样。

最终,我选择了文档格式化程序的自定义,方法是在spec/support文件夹中的某个位置包含以下代码(以确保自动加载):

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

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

这是我所做的...在我的规范中添加了一个 NextStep("消息")方法,该方法使用 gem 将"消息"输出到控制台awesome_print以便我可以为其着色,也可以输出到记录器。

  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

有点黑客,但它在运行 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"

最新更新