cucumber/ruby: possible to output the “puts” to a

2019-02-24 05:02发布

I've got some ruby tests that are calling different modules, classes where they detail what they're doing with some "puts" commands during execution.

If you run those tests in the console then you will see the output of the "puts" command in the console but if you run the tests with the option:

ruby --format html --output file.html

then all that information is lost. Is there a way to log simple string messages inside the HTML report?

2条回答
你好瞎i
2楼-- · 2019-02-24 05:16

I tried the following steps:

When /^I do something$/ do
  puts "Hello"
end

Then /^something happens$/ do
end

...with the following command:

cucumber -f html -o results.htm

...when I opened up the results.html file in a browser, it displayed the "Hello" message just after displaying the step. I've attached the pertinent section of the HTML output so you can see that the output from puts is there:

<!-- the first step -->
<li id='features_thing_feature_4' class='step passed'>
    <div class="step_name">
        <span class="keyword">When </span>
        <span class="step val">I do something</span>
    </div>
    <div class="step_file">
        <span>features/step_definitions/thing_steps.rb:1</span>
    </div>
</li>
<!-- anything that the above step passed to `puts` -->
<li class="step message">Hello</li>
<!-- the second step -->
<li id='features_thing_feature_5' class='step passed'>
    <div class="step_name">
        <span class="keyword">Then </span>
        <span class="step val">something happens</span>
    </div>
    <div class="step_file">
        <span>features/step_definitions/thing_steps.rb:5</span>
    </div>
</li>

What that demonstrates is that when cucumber's puts method is called (ie: directly from within a step) the output will be included in the html output. But if the puts call is from somewhere else (eg: your modules) then it won't be included. You could consider moving your puts calls from the modules to the steps. Also, using puts isn't really best practice so you may want to consider removing it altogether...

查看更多
ら.Afraid
3楼-- · 2019-02-24 05:27

You can remember World in Before hook of each scenario:

# features/support/env.rb
Before do |scenario|
  $world = self
end

Then in your support classes and modules outside world you can use puts as:

$world.puts 'something'

Also you can get/set Cucumber instance variables as:

$world.instance_variable_get(:@user)
$world.instance_variable_set(:@user, user)

I also prefer to extract those 2 methods to helpers for better visibility:

module Helpers
  def get_scenario_variable(symbol)
    $world.instance_variable_get(symbol)
  end

  def set_scenario_variable(symbol, value)
    $world.instance_variable_set(symbol, value)
  end
end

Then you can include this module where you need those methods

查看更多
登录 后发表回答