我正在使用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
答案 0 :(得分:3)
更改为ERB语法(<%= ... %>
),然后在步骤定义中,通过ERB运行字符串:
require 'erb'
When %r{^I POST (.+) with data:$} do |path, data_str|
data = ERB.new(data_str).result(binding)
# ...
end
答案 1 :(得分:2)
这方面的两半是情景方面:
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
答案 2 :(得分: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