2

我正在使用 Cucumber 将 JSON 发送到一些 API 操作。在一个实例中,我需要知道在 API 调用之前构建的对象的 ID 并将该 ID 传入。

我想做这个:

  Scenario: Creating a print from an existing document
    Given I am logged in as "foo@localhost.localdomain"
      And I have already built a document
     When I POST /api/prints with data:
       """
       {
         "documentId":"#{@document.id}",
         "foo":"bar",
         "etc":"etc" 
       }
       """
     Then check things

这不起作用,因为"""字符串不会像双引号字符串那样插入变量。该I have already built a document步骤构建@document对象,所以我不提前知道我的 ID 是什么。如果重要的话,我将 MongoDB 与 mongoid 一起使用,而我手动设置 ID 的努力被证明是徒劳的。

有没有一种干净的方法可以做到这一点?

环境:

ruby: 1.8.7
rails: 3.0.1
cucumber: 0.9.4
cucumber-rails: 0.3.2
4

3 回答 3

3

更改为 ERB 语法 ( <%= ... %>),然后在您的步骤定义中,通过 ERB 运行字符串:

require 'erb'

When %r{^I POST (.+) with data:$} do |path, data_str|
  data = ERB.new(data_str).result(binding)
  # ...
end
于 2010-12-07T14:47:15.713 回答
2

ERB 是一种推迟评估的方法,但也许,西奥,这更干净一些?

这其中的两半是场景方面:

Scenario: Creating a print from an existing document
  Given I am logged in as "foo@localhost.localdomain"
    And I have already built a document
  When I POST /api/prints with data:
   # outer, single quotes defer evaluation of #{@document}
   '{
     "documentId":"#{@document.id}",
     "foo":"bar",
     "etc":"etc" 
   }'
 Then check things

以及步骤定义方面:

When %r{^I POST (.+) with data:$} do |path, data_str|
  # assuming @document is in scope...
  data = eval(data_str)
  # ...
end
于 2010-12-07T19:27:20.170 回答
1

我建议使用场景大纲和示例,例如

Scenario Outline: Posting stuff
....
When I POST /api/prints with data:
   """
   {
     "documentId": <document_id>,
     "foo":"bar",
     "etc":"etc" 
   }
   """
Then check things

Examples: Valid document
| document_id |
| 1234566     |

Examples: Invalid document
| document_id |
| 6666666     |

在例子中。这至少可以清楚地说明这些值的来源。在此处检查场景大纲中的替换http://cukes.info/step-definitions.html

于 2014-06-26T14:22:31.537 回答