16
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHPでコントローラーのPOSTをテストする

Last updated at Posted at 2015-04-17

testActionの第二引数でPOSTするデータを渡すとテストできます。

CommentsControllerTest.php
public function testAdd() {
    $data = array(
        'Comment' => array(
            'body' => 'this is comment test'
        )
    );
    $this->testAction('/comments/add', array('method' => 'post', 'data' => $data));
}

こんな感じ。

ファイルのアップロードを伴うPOSTをテストしたい場合は、ファイルをPOSTした時に$_FILESにセットされる想定のものをファイルの値に入れて渡せば良いようです。

CommentsControllerTest.php
public function testAdd() {
    $data = array(
        'Comment' => array(
            'body' => 'this is comment test',
            'img_file' => array(
                'name' => 'picture.jpg',
                'type' => 'image/jpg',
                'tmp_name' => ROOT . DS . APP_DIR . DS . 'Test' . DS . 'Fixture' . DS . 'picture.jpg',
                'error' => UPLOAD_ERR_OK,
                'size' => 58915
            )
        )
    );
    $this->testAction('/comments/add', array('method' => 'post', 'data' => $data));
}

テスト用のファイルをFixtureディレクトリの下とかに置いておき、tmp_nameにその場所を書きます。

16
11
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
16
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?