2016-05-08 47 views
1

我在Cucumber Background部分放置了一個調試打印語句。爲什麼黃瓜背景的輸出只顯示一次?

由於Background對於每個場景都會執行一次,因此我預計每個場景都會看到Background的輸出。但是輸出只顯示一次。爲什麼?

下面是一個簡單的例子,說明我的問題:

計算器/功能/ adding.feature:

Feature: Adding 

Background: 
    Given calculator is ready 

Scenario: Add two numbers 
    Given the input "2" and "2" 
    When the calculator is run 
    Then the output should be "4" 

Scenario: Add another two numbers 
    Given the input "2" and "3" 
    When the calculator is run 
    Then the output should be "5" 

計算器/功能/ step_definitions/calculator_steps.rb:

counter = 0 

Given(/^calculator is ready$/) do 
    puts "*** background ***" 
    counter += 1 
end 

Given(/^the input "([^"]*)" and "([^"]*)"$/) do |x1, x2| 
    @x1 = x1 
    @x2 = x2 
end 

When(/^the calculator is run$/) do 
    @output = `ruby calc.rb #{@x1} #{@x2}` 
end 

Then(/^the output should be "([^"]*)"$/) do |expected_output| 
    expect(@output).to eq(expected_output) 
    puts "counter=#{counter}" 
end 

calculator/calc.rb:

x1 = ARGV[0].to_i 
x2 = ARGV[1].to_i 

print ("#{x1+x2}") 

這裏是輸出場景被執行時:

$ cucumber 
Feature: Adding 

    Background:     # features/adding.feature:3 
    Given calculator is ready # features/step_definitions/calculator_steps.rb:3 
    *** background *** 

    Scenario: Add two numbers  # features/adding.feature:6 
    Given the input "2" and "2" # features/step_definitions/calculator_steps.rb:8  
    When the calculator is run # features/step_definitions/calculator_steps.rb:13 
    Then the output should be "4" # features/step_definitions/calculator_steps.rb:17 
     counter=1 

    Scenario: Add another two numbers # features/adding.feature:11 
    Given the input "2" and "3"  # features/step_definitions/calculator_steps.rb:8 
    When the calculator is run  # features/step_definitions/calculator_steps.rb:13 
    Then the output should be "5" # features/step_definitions/calculator_steps.rb:17 
     counter=2 

2 scenarios (2 passed) 
8 steps (8 passed) 
0m0.094s 

我期望看到的線*** background ***兩次(因爲Background被執行兩次),但它是僅示出一次。爲什麼?

回答

1

在黃瓜上打印的信息Background步驟只打印一次,因爲當黃瓜執行一個步驟並在黃瓜的控制下打印時,捕獲標準輸出。在Background步驟中打印的消息與步驟名稱一起打印:僅在輸出開始時打印一次。

因此,每次Background運行時查看打印的消息的方式與每次運行Background時查看步驟名稱的方式相同。已經有了一個問題和答案,但它不適用於當前版本的Cucumber(我有2.3.3),所以我寫了一個新問題的答案,顯示how to print everything that Background prints before every scenario

+0

感謝Dave,您爲Cucumber 2.3.3所描述的解決方案適用於我,並且由於這通常用於調試目的,因此在本地修改gem並不是問題。 –