web-k.log

RubyやWebをメインに技術情報をのせていきます

FabricationとCucumberの連携

| Comments

前回Fabricationの続きで、Cucumberと連携する方法についてここに記載します。

Cucumber

インストール

step_definitionsフォルダに便利な cucumber_steps を生成してくれるツールがgemの中にパッケージ化されている。 Gemfileのdevelopment環境にcucumber系を含めている必要がある。

1
2
$ rails generate fabrication:cucumber_steps
# => create  features/step_definitions/fabrication_steps.rb

Step Definitions

WidgetモデルのFabricatorが定義されていれば、下記のように書くだけでFabricateできる。

1
Given 1 widget

Widgetモデルの属性を指定してFabricateすることもできる。

1
2
3
4
Given the following widget:
  | name      | widget_1 |
  | color     | red      |
  | adjective | awesome  |

複数も可

1
Given 10 widgets

属性付きで複数Fabricateする。

1
2
3
4
5
Given the following widgets:
  | name     | color | adjective |
  | widget_1 | red   | awesome   |
  | widget_2 | blue  | fantastic |
  ...

既にFabricateされた”widget”に”wockets”を所属させる。

1
And that widget has 10 wockets

既にFabricateされた”widget”に”wockets”を属性を与えて所属させる。

1
2
3
And that widget has the following wocket
  | title    | Amazing |
  | category | fancy   |

既にFabricateされた”widget”と”wockets”を関連付ける。

1
And that wocket belongs to that widget

データベースにいくつのオブジェクトが保持されているか検証する。

1
Then I should see 1 widget in the database

オブジェクトの中身も検証できる。

1
2
3
4
Then I should see the following widget in the database
  | name  | Sprocket |
  | gears | 4        |
  | color | green    |

Transforms

cucumberのステップでテーブルを変換できる。縦横のテーブルでカラムの値を再配置できる。 spec/fabricatorsフォルダにおいておけば、何とでも設定しておける。

例として、全てのフィールドの”company”に変換の定義をする。lambda には返り値の属性をセットしたい文字列を置く。 その結果、”company”のインスタンスオブジェクトが生成される。

1
Fabrication::Transform.define(:company, lambda{ |company_name| Company.where(name: company_name).first })
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Scenario: a single object with transform to apply
  Given the following company:
    | name | Widgets Inc |
  Given the following division:
    | name    | Southwest   |
    | company | Widgets Inc |
  Then that division should reference that company

Scenario: multiple objects with transform to apply
  Given the following company:
    | name | Widgets Inc |
  Given the following divisions:
    | name      | company     |
    | Southwest | Widgets Inc |
    | North     | Widgets Inc |
  Then they should reference that company

divisions を生成したときに、lambdaによって”company”オブジェクトに渡されている。

特定のモデルのスコープにだけ適用したい場合は、only_forを使う。

1
Fabrication::Transform.only_for(:division, :company, lambda { |company_name| Company.where(name: company_name).first })

Comments