我正在使用黄瓜将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 对象,所以我不知道我的身份证会是什么。如果重要的话,我正在将MongoDB与Mongoid一起使用,而我为手动设置ID的努力被证明是徒劳的。

有什么干净的方法可以实现这一目标吗?

环境:

ruby: 1.8.7
rails: 3.0.1
cucumber: 0.9.4
cucumber-rails: 0.3.2
有帮助吗?

解决方案

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

require 'erb'

When %r{^I POST (.+) with data:$} do |path, data_str|
  data = ERB.new(data_str).result(binding)
  # ...
end

其他提示

ERB是推迟评估的一种方法,但也许是Theo,这有点清洁吗?

这两半是场景方面:

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

我建议使用场景大纲和示例使用类似

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top