LoginSignup
9
9

More than 5 years have passed since last update.

WordPress + PHPUnitで$GETの値を使った条件分岐のテスト

Last updated at Posted at 2015-07-17

簡単だと思ってたらすごくはまってしまった。。。

WordPressで独自のRSSフィードを生成する必要があって、クライアントの要望で以下のようにデフォルトのフィードのURLにtypeというパラメータを渡してそれに基づいてカスタムフィードを発火させる必要があった。

http://example.com/feed/?type=hoge

こんな場合、以下のような感じでいろいろなフックで条件分岐を入れるわけですが、phpunitと叩いても期待通りに発火してくれない。。。

add_filter( 'the_excerpt_rss', function( $excerpt ){
    if ( is_feed() && isset( $_GET['type'] ) && 'hoge' === $_GET['type'] ) {
        return do_something();
    } else {
        return $excerpt;
    }
} );

こんな時は、テスト側で以下のようにset_query_var()を使えばオッケー。

class YahooFeed_Test extends WP_UnitTestCase
{
    /**
     * @test
     */
    public function is_custom_feed()
    {
        $this->go_to( '/feed/' );
        set_query_var( 'type', 'hoge' );
        $this->assertTrue( do_something_else() );
    }
}

さらにプラグイン側は$_GETを直接使わずに以下のようにget_query_var()を使う。

add_filter( 'query_vars', function( $vars ){
    $vars[] = 'type';
    return $vars;
} );

add_filter( 'the_excerpt_rss', function( $excerpt ){
    if ( is_feed() && get_query_var( 'type' ) ) {
        return do_something();
    } else {
        return $excerpt;
    }
} );
9
9
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
9
9