我只是在学习行为,所以如果这是非常基本的,我很抱歉。 我有这样的场景:
Scenario: Create Task
Given I have the JSON payload:
"""
{
"task_list_id" : 3,
"title" : "From Behat",
"display_order" : 1
}
"""
When I send a POST request to task
Then one SQL ident is created
Scenario: Get the Task
When I send a GET request to "tasklist/{id}/tasks"
Then The response code should be 200
And The response content type should be "application/json"
第一个场景建立连接,然后 JSON 返回一个整数值。 我现在希望将 that 值替换到 URL 具有 {id} 占位符的下一个场景中。
我尝试在第一个场景的 FeatureContext.php 文件中将 $this->output 设置为正文(返回的整数),然后在第二个场景中执行 preg_replace 将 {id} 更改为整数。 看来,当运行第二个场景时,输出在调用该场景之前被清空。
这些是我针对上述内容的上下文方法:
/**
* @Then One SQL ident is created
*/
public function theResponseBodyShouldBeAnInteger() {
$this->theResponseContentTypeShouldBe('application/json');
$this->theResponseCodeShouldBe(201);
$body = $this->response->getBody()->getContents();
if (!ctype_digit($body)) {
throw New Exception(sprintf('Expected integer response but got "%s".', $body));
}
$this->output = $body;
echo "Output is '$this->output'\n";
}
/**
* @When I send a :method request to :uri
*
* @param $method
* @param $uri
*/
public function iSendARequestTo($method, $uri)
{
echo "Output is '$this->output'\n";
$uri = str_replace('{id}', $this->output, $uri);
try {
if ($method == 'POST' || $method == 'PATCH') {
$this->response = $this->client->request($method, $uri, ['json' => $this->requestPayload]);
} else {
$this->response = $this->client->request($method, $uri);
}
} catch (GuzzleHttp\Exception\ClientException $ex) {
throw new Exception($uri . "\n" . $ex->getResponse()->getBody()->getContents());
}
}
当然是空白的,场景是而且应该是独立的,你在第一个场景中保存的任何内容都会在场景完成后丢失。
执行此操作的一种方法是写入文件并从文件中读取。
无论如何,我看到第一个场景的验证包括第二个场景的验证,唯一的区别是在第一个场景中您保存响应的正文,这不是一个很好的主意,也不是保存数据的好做法验证步骤。
尽量重复利用。
场景保持独立。您应该能够在没有第一个场景的情况下运行第二个场景。
高级示例,只是一个意见:
Scenario: Api - check response of the created task
Given I have the JSON payload
When I create a task using POST request -> create request, make sure is successful and save response
And I send a GET request to created task -> use saved response to do what you need
Then the response code should be 200
And the response code should be "application/json"
另一个例子:
Scenario: Api - check response of the created task
Given I have have a task based on JSON: -> create request, make sure is successful and save response
When I send a GET request to created task -> use saved response to do what you need
Then the response code should be 200
And the response code should be "application/json"
这些只是一些示例,我不知道其功能,我相信您可以做得更好,始终在创建步骤时牢记您的项目业务语言,以便稍后理解它们。
任务列表方法 您需要确保您有一个任务列表,这是必需的,您需要的是检查任务列表是否可用(例如按标题),如果是,则不执行任何其他操作创建任务列表。