我正在使用Cucumber将JSON发送到某些API操作。在一个实例中,我需要知道在API调用之前构建的对象的ID并传入该ID。
我想做这个:
Scenario: Creating a print from an existing document
Given I am logged in as "[email protected]"
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
更改为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 "[email protected]"
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