LoginSignup
4
3

More than 5 years have passed since last update.

WordPressで任意の$postオブジェクトを現在の$postとしてセットして、the_content()等の出力内容をテスト

Last updated at Posted at 2015-01-08

以下のようなテストをしたいときに便利。

  • ショートコードが期待通りに発火する?
  • the_contentなどのフィルターフックが発火してる?

テストの流れ。

  1. テスト用の投稿を保存
  2. get_post()で$postオブジェクトを取得する。
  3. setup_postdata()で現在のカレントの$postにセットする。
  4. the_content()などのテンプレートタグの出力をテストする。
<?php

class Sample_Test extends WP_UnitTestCase
{
    /**
     * @test
     */
    function sample_test()
    {
        $args = array(
            'post_title' => 'Hello',
            'post_author' => 1,
            'post_content' => 'Hello World!',
            'post_status' => 'publish',
            'post_date' => '2014-01-01 00:00:00',
        );

        $this->setup_postdata( $args );

        /*
         * the_content()の結果に対してテスト
         */
        $this->expectOutputString( "<p>Hello World!</p>\n" );
        the_content();
    }

    /**
     * Add post and post be set to current.
     * 
     * @param  array $args A hash array of the post object.
     * @return none
     */ 
    public function setup_postdata( $args )
    {
        global $post;
        global $wp_query;

        $wp_query->is_singular = true;

        $post_id = $this->factory->post->create( $args );
        $post = get_post( $post_id );
        setup_postdata( $post );
    }
}
4
3
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
4
3