LoginSignup
5
0

More than 3 years have passed since last update.

D言語でBDDするcucumber-dの使い方

Last updated at Posted at 2019-12-22

はじめに

cucumber-dを作ったので、簡単に使い方を紹介します。

cucumber-man.png

cucumber-d

読んで字のごとく、CucumberのD言語実装です。
以下のことができます。

  • Gherkinで書かれたfeatureファイルのパース
  • D言語で書かれたStepファイルの実行

使い方

httpbinを例に解説します。

$ tree examples/httpbin/
examples/httpbin/
|-- bin
|   `-- .gitkeep
|-- features
|   |-- step_definitions
|   |   `-- steps.d
|   |-- support
|   |   `-- env.d
|   `-- httpbin.feature
|-- .gitignore
|-- dub.json
`-- dub.selections.json

以下のfeatureファイルでhttpbin.orgにアクセスし、ステータスコードを検証します。

features/httpbin.feature
Feature: Assert httpbin response

  Scenario: httpbin returns 200 OK
     When the user sends a GET request to http://httpbin.org/
     Then the response status should be 200

  Scenario Outline: httpbin returns 4xx
     When the user sends a GET request to http://httpbin.org/status/<codes>
     Then the response status should be <status>

    Examples:
     | codes | status |
     | 400   | 400    |
     | 404   | 404    |

Stepファイル

StepファイルをD言語で書きます。
@Given, @When, @Then のUDAが付与されているメソッドがStepのキーワードに対応します。
ここでは値の検証にunit-threadedを使っています。
cucumber-dは実行時にExceptionのみcatchするため、値の検証にassertが使えないので注意が必要です。

features/step_definitions/steps.d
module step_definitions.steps;

import cucumber.keywords : When, Then;
import requests : Request, Response;
import unit_threaded.assertions : should;

///
Response response;

///
@When("^the user sends a GET request to (?P<url>.*)$")
void sendAGetRequestTo(string url)
{
    response = Request().get(url);
}

///
@Then("^the response status should be (?P<code>[0-9]+)$")
void theResponseStatusShouldBe(int code)
{
    response.code.should == code;
}

app.dに相当するもの

ここでは、features/support/env.d に配置しています。
CucumberのRuby実装等は必要に応じてファイルを作成しますが、cucumber-dでは必須です。
先ほどのstep_definitions.stepsを指定してCucumberCommandlineクラスのrunを呼び出します。

features/support/env.d
module env;

import cucumber.commandline : CucumberCommandline;

int main(string[] args)
{
    return (new CucumberCommandline).run!("step_definitions.steps")(args);
}

コンパイルと実行

上記のapp.dに相当するものが実行され、features/ディレクトリ以下のfeatureファイルが実行されます。

compile_and_run

おわりに

Cucumberの主たる機能の内、以下の機能が未実装なので今後実装予定です。

  • StepへのTableData渡し
  • StepへのDocString渡し
  • --format json
  • Rule:
  • Language:

未実装の機能がいくつかあるため本家と同じようには動かせませんが、Cucumberの基本的な機能は使える状態です。
是非使ってみてください。

5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0