LoginSignup
18
18

More than 5 years have passed since last update.

Python de BDD (Lettuceで)

Last updated at Posted at 2012-07-23

インストール

いつも通り pip で。

$ pip install lettuce

Feature を書く

拡張子を .feature にすればいいですが、features ディレクトリに書く方が気持ちいい気がすします。日本語にも対応してるそうです。

features/example.feature
Feature: a cookie in a bug
  In order to eat a cookie
  I carry a bug

Scenario: simple test
  Given I have a bug
  Then a cookie exists in the bug

で、lettuce を実行すると、書くべき step のテンプレを表示してくれます。

#You can implement step definitions for undefined steps with these snippets:

# -*- coding: utf-8 -*-
from lettuce import step

@step(u'Given I have a bug')
def given_i_have_a_bug(step):
    assert False, 'This step must be implemented'
@step(u'Then a coookie exists in the bug')
def then_a_cookie_exists_in_the_bug(step):
    assert False, 'This step must be implemented'

pending が無い・・・のかな?

Step を書く

作った feature と同じディレクトリに、.py で作ります。まずはコピペ。

features/example.py
# -*- coding: utf-8 -*-
from lettuce import step

@step(u'Given I have a bug')
def given_i_have_a_bug(step):
    assert False, 'This step must be implemented'
@step(u'Then a coookie exists in the bug')
def then_a_coookie_exists_in_the_bug(step):
    assert False, 'This step must be implemented'

このままでは、すべて Fail するので、それっぽく書き換えます。

example.py
# -*- coding: utf-8 -*-
from lettuce import *
import sys
import bug # これから作る

@step(u'Given I have a (.*)$')
def given_i_have_a_bug(step, arg):
    cls = getattr(sys.modules[arg], arg[0].upper() + arg[1:])
    world.__dict__[arg] = cls()
    assert world.__dict__[arg], arg + ' must be an instance'

@step(u'Then a cookie exists in the (.*)$')
def then_a_coookie_exists_in_the_bug(step, obj):
    assert world.__dict__[obj].cookie, arg1 + ' should return True'

テスト!

lettuce を実行するだけです。

いざ実装

ちょっとしょぼすぎますが。。。

bug.py
class Bug(object):
  def __init__(self):
    self.cookie = True

まとめます

  • ステップの import はテンプレから書き換える
  • world で各ステップ共有の変数を作る
  • @step は ruby と似てるので書きやすい
  • @step の文字列と直後の関数名は同じじゃなくて良い
  • ステップを書くのが難しい(これだけで2時間かかった)
  • もっと良いサンプルが世の中にはたくさんある orz
18
18
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
18
18