WordPressでビルトインサーバーで開発環境を構築しテーマをテスト : WordPress

Pocket

ビルトインサーバーでWordPressの開発環境を構築します。
合わせてテスト環境も構築します。またTravis CIを使いサーバーテストも行います。

  1. 開発用MySQLユーザー、DB作成
  2. 開発用WordPressインストール
  3. WP-CLIインストール
  4. ローカルのテスト環境構築
  5. 自作テーマのテスト
  6. Travis CIでテーマをテスト

PHP, MySQL

ローカルのPHPとMySQLを使用します。
(私の環境環境はHomebrewでインストールしました。)

DB – MySQL –

起動・停止・再起動

$ mysql.server start
$ mysql.server stop
$ mysql.server restart

DB情報

使用するデータベース情報です。

項目
DB名 wordpress_local
DBユーザー名 wordpress
DBパスワード wordpress
DBホスト localhost

データベース作成

$ CREATE DATABASE wordpress_local DEFAULT CHARACTER SET utf8

ユーザー作成

ユーザーを作成しwordpress_localへ全ての権限を付与します。

$ GRANT ALL PRIVILEGES ON `wordpress_local`.* TO 'wordpress'@'localhost' IDENTIFIED BY 'wordpress' WITH GRANT OPTION;

WordPressインストール

WordPressダウンロード

下記リンクから最新版WordPressをダウンロードし展開します。

https://ja.wordpress.org/

ビルトインサーバー起動

説明を簡単にするためダウンロードファイルを展開したwordpressディレクトリをドキュメントルートとします。

$ cd /path/to/wordpress
$ php -S localhost:8080

インストール

ブラウザからhttp://localhost:8080へアクセスするとインストーラー画面が表示されます。
先ほど作成したデータベース情報をもとにインストールします。

ビルトインサーバーは.htaccessを利用できないので、
パーマリンクの形式によってはルーティングのためのスクリプトが必要になります。

ルーティングスクリプトについてはAppendixで記載しています。

WP-CLI

テスト用の雛形作成にWP-CLIを使います。
WP-CLIがインストールされていないときは下記手順でインストールできます。

Command line interface for WordPress | WP-CLI

$ cd /path/to/wordpress
$ curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
$ chmod +x wp-cli.phar
$ sudo mv wp-cli.phar /usr/local/bin/wp

インストール確認

$ wp --info

/user/local/binはパスが通っていることを前提にしています。

テーマのテスト

テスト環境構築の流れ

  • プラグイン雛形作成
    最終的な目標はテーマのテストですがまずプラグイン用の雛形を作成します。
  • 必要ファイルをテーマディレクトリへコピー・修正
    プラグイン用雛形から必要なファイルをテーマディレクトリへ修正し配置します。
  • テスト用WordPress・DB作成作成
    bin/install-wp-tests.shを実行しテスト用WordPressとDBを準備します。

プラグイン雛形作成

例としてmy-pluginという名前でプラグインの雛形を作成します。

$ cd /path/to/wordpress
$ wp scaffold plugin my-plugin

// 作成される雛形
my-plugin
    |-- bin                         <-- テーマへコピー
        |-- install-wp-tests.sh 
    |-- tests
        |-- bootstrap.php           <--- テーマへコピー・編集
        |-- test-sample.php
        |-- test-my-plugin.php
    |-- .travis.yml                 <--- テーマへコピー
    |-- phpunit.xml                 <--- テーマへコピー・編集
    |-- readme.txt
    |-- my-plugin.php

テーマへ必要ファイルをコピー・編集

プラグイン用雛形の中で必要なファイルをテーマディレクトリへコピーし必要な編集必要な編集を行います。
下記ファイル/ディレクトリをコピーします。

  • bin/install-wp-tests.sh
  • .travis.yml
  • phpunit.xml
  • tests/bootstrap.php

テーマディレクトリ構成

my-theme
    |
    |-- bin
        |-- install-wp-tests.sh
    |...
    |-- tests
        |-- bootstrap.php
        |-- test-sample.php
    |-- index.php
    |...
    |-- phpunit.xml
    |-- .traivs.yml
    |...
    |-- style.css

phpunit.xml

plugin用に作成されたphpunit.xmlをテーマディレクトリへコピーし編集します。

下記サンプルはテストファイルはtestsディレクトリのプレフィックスtest-がついたファイルです。
テスト対象はincディレクトリのファイルになります。

<phpunit
    bootstrap="tests/bootstrap.php"
    backupGlobals="false"
    colors="true"
    convertErrorsToExceptions="true"
    convertNoticesToExceptions="true"
    convertWarningsToExceptions="true"
    >
    <testsuites>
        <testsuite>
            <directory prefix="test-" suffix=".php">./tests/</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist>
            <directory>./inc</directory>
        </whitelist>
    </filter>
</phpunit>

tests/bootstrap.php

plugin用に作成されたbootstrap.phpをテーマディレクトリへコピーしファイルを編集します。
WordPress Theme開発でPHPUnitを使う – Qiita

<?php
$_tests_dir = getenv( 'WP_TESTS_DIR' );
if ( ! $_tests_dir ) {
    $_tests_dir = '/tmp/wordpress-tests-lib';
}

require_once $_tests_dir . '/includes/functions.php';

function _manually_load_plugin() {
    register_theme_directory( dirname( __FILE__ ) . '/../../' );
    switch_theme( 'my-theme' );
}

tests_add_filter( 'muplugins_loaded', '_manually_load_plugin' );

require $_tests_dir . '/includes/bootstrap.php';

テスト用WordPress・DB構築スクリプト

$ cd $(wp plugin path --dir my-theme)
$ bash bin/install-wp-tests.sh wordpress_test wordpress wordpress localhost latest

シェルスクリプトへ渡す引数は以下の通りです。

項目 備考
第1引数 DB名 wordpress_test
第2引数 DB ユーザー名 wordpress
第3引数 DB パスワード wordpress
第4引数 DB ホスト localhost

tmp(Macは/private/tmpのエイリアス)へwordpressとwordpress-tests-libがインストールインストールされます。
wordpress/tests-lib/wp-tests-config.phpが設定ファイルです。

下記警告が出たときは強制終了(ctrl + c)しDBは手動で作成します。
(install-wp-tests.shの第5引数skip-database-creationへtrueを渡すとDB作成をく省略します。)

Warning: Using a password on the command line interface can be insecure.

Travis CI

Travis CI – Test and Deploy Your Code with Confidence

.travis.ymlをテーマディレクトへコピーします。

デフォルトはmasterブランチブランチをpushしたときに自動テストが実行されます。
.travis.ymlでPHPのバージョン、WordPressのバージョンを指定し複数の組み合わせをテストできます。

language: php

notifications:
  email:
    on_success: never
    on_failure: change

branches:
  only:
    - master

php:
  - 5.3
  - 5.6

env:
  - WP_VERSION=latest WP_MULTISITE=0
  - WP_VERSION=3.8 WP_MULTISITE=0
  - WP_VERSION=4.6.1 WP_MULTISITE=0

matrix:
  include:
    - php: 5.3
      env: WP_VERSION=latest WP_MULTISITE=1

before_script:
  - bash bin/install-wp-tests.sh wordpress_test root '' localhost $WP_VERSION

script: phpunit

Apendix

PHP, MySQLインストール

Homebrewでインストール済みのプラグインは下記方法で確認できます。

$ brew list

ビルトインサーバーのルーティング

ビルトインサーバーは.htaccessを利用できないので、
パーマリンクの形式によってはルーティングのためのスクリプトが必要になります。

ルーティングスクリプトが必要な例

http://localhost:8080//%category%/%post_id%.html

※ index.php(フロントコントローラー)をURLに含むときは正常にルーティンされます。
※ 例えば下記のようなパーマリンクも扱えます(拡張し.htmlがついていないこと注意。)

http://localhost:8080//%category%/%post_id%

ルータースクリプト wordpress/router.php

ビルトインサーバーは起動時に引数で渡したPHPファイルを最初に実行します。
その機能を利用してルーティングを行います。
例ではrouter.phpという名前のファイルをwordpressディレクトリへ作成しています。

$ php -S localhost:8080 ./router.php

router.php

ルーティングスクリプトは下記記事のコードを利用しています。
http://ripeworks.com/run-wordpress-locally-using-phps-buily-in-web-server/

<?php
$root = $_SERVER['DOCUMENT_ROOT'];
chdir($root);
$path = '/'.ltrim(parse_url($_SERVER['REQUEST_URI'])['path'],'/');
set_include_path(get_include_path().':'.__DIR__);
if(file_exists($root.$path))
{
    if(is_dir($root.$path) && substr($path,strlen($path) - 1, 1) !== '/')
        $path = rtrim($path,'/').'/index.php';
    if(strpos($path,'.php') === false) return false;
    else {
        chdir(dirname($root.$path));
        require_once $root.$path;
    }
}else include_once 'index.php';

コメント

No comments yet.

コメントの投稿

改行と段落タグは自動で挿入されます。
メールアドレスは表示されません。