How to build a WordPress plugin by TDD

Sponsored · SiteGround - Reliable hosting with speed, security, and support you can count on. →
kazweda
November 07, 2015

How to build a WordPress plugin by TDD

WordBench愛媛 - 秋のお茶会のプレゼン資料です。
VCCW環境でTDDを試してみました。

kazweda

November 07, 2015

Annual Pro sale · Save $30

Have presentations of your own?

Share with private links, password protection, and more control over your work.

Transcript

30 slides
  1. テストコードを書こう 参考までに、昨年の Coderetreat "Global Day of Coderetreat 2014 in Matsuyama"

    agile459.doorkeeper.jp/events/16066 ペア( 2 人一組)でプログラムの問 題を TDD で解くトレーニングのイ ベント。世界同時(同日)開催。
  2. 環境が整っている前提で ... 仮想環境(べいぐらんと)を起動 $ vagrant up 仮想環境に ssh で入る $

    vagrant ssh wordpress ディレクトリへ移動 $ cd /var/www/wordpress WP-CLI でプラグインのひな形を生成 $ wp scaffold plugin my-counter
  3. PHPUnit 用の WordPress 環境準備 プラグインのディレクトリに移動 $ cd $(wp plugin path

    --dir my-counter) テスト用 WordPress 環境を作成 $ bash bin/install-wp-tests.sh wordpress_test root 'wordpress' localhost latest mysqladmin: CREATE DATABASE failed; error: 'Can't create database 'wordpress_test'; database exists' (テスト用DBはすでに作られている様子。)
  4. テスト用のクラスを追加 $ touch tests/test-my-counter.php ショートコードを実行すると0が返る <?php class MyCounterTest extends WP_UnitTestCase

    { function test_my_counter_shortcode() { $count = do_shortcode( '[my_counter]' ); $this->assertEquals('0', $count); } }
  5. shortcode の処理を実装 class MyCounter { public function __construct() { add_shortcode(

    'my_counter', array( $this, 'mycounter_shortcode' )); } public function mycounter_shortcode($p) { return '0'; } }
  6. Widget でショートコードを使う フィルターが必要でした。 class MyCounterTest extends WP_UnitTestCase { function test_my_counter_shortcode()

    { $count = do_shortcode( '[my_counter]' ); $this->assertEquals('0', $count); $this->assertTrue( has_filter('widget_text', 'do_shortcode') ); } }
  7. Widget でショートコードを使う フィルターを追加。 class MyCounter { public function __construct() {

    add_shortcode( 'my_counter', array( $this, 'mycounter_shortcode' )); add_filter('widget_text', 'do_shortcode' ); } ...
  8. カウントアップ class MyCounterTest extends WP_UnitTestCase { ... function test_counter_increment() {

    $cnt0 = do_shortcode( '[my_counter]' ); $cnt1 = do_shortcode( '[my_counter]' ); $this->assertEquals( $cnt1, $cnt0 + 1 ); } ... カウントアップのテストコード追加。
  9. カウントアップを実装 class MyCounter { ... public function mycounter_shortcode($p) { $count

    = get_option( 'my_counter' ) + 1; update_option( 'my_counter', $count ); return $count; } ... 今回は WordPress のオプション値を利用。

More Decks by kazweda

Other Decks in Programming