2015-01-18 3 views
1

다른 사람이이 문제를 발견했는지 궁금합니다. 제프리 웨이 (Jeffrey Way)가 Laravel에서 테스트 한 책을 살펴보고 컨트롤러를 테스트하는 방법을 설명하는 장을 다룰 것입니다. - 내가이 책에서 예를 따르Laravel 4.2 : assertRedirectedToRoute 테스트가 실패했습니다.

내가 메시지가 :

를 분명히는 \ 응답 개체 (...을)를 분명히 '클래스의 인스턴스의 HTTP \ 것을 주장 실패 \ HTTP를 \ RedirectResponse ". (그냥이 특정 시나리오를 테스트하려면)

public function testStoreFails() 
    { 

     $input = ['title' => '']; 

     $this->mock 
       ->shouldReceive('create') 
       ->once() 
       ->with($input); 

     $this->app->instance('Post', $this->mock); 

     $this->post('posts', $input); 

     $this->assertRedirectedToRoute('posts.create'); 

     $this->assertSessionHasErrors(['title']); 

    } 

그리고 컨트롤러의 매우 간단한 방법 : 나는 AssertionsTrait::assertRedirectedTo를 볼 수있는에서

public function create() 
    { 

     $input = Input::all(); 

     $validator = Validator::make($input, ['title' => 'required']); 

     if ($validator->fails()) { 

      return Redirect::route('posts.create') 
        ->withInput() 
        ->withErrors($validator->messages()); 

     } 

     $this->post->create($input); 

     return Redirect::route('posts.index') 
       ->with('flash', 'Your post has been created!'); 

    } 

내 시험은 다음과 같다 예 : Illuminate\Http\RedirectResponse

/** 
    * Assert whether the client was redirected to a given URI. 
    * 
    * @param string $uri 
    * @param array $with 
    * @return void 
    */ 
    public function assertRedirectedTo($uri, $with = array()) 
    { 
     $response = $this->client->getResponse(); 

     $this->assertInstanceOf('Illuminate\Http\RedirectResponse', $response); 

     $this->assertEquals($this->app['url']->to($uri), $response->headers->get('Location')); 

     $this->assertSessionHasAll($with); 
    } 

    /** 
    * Assert whether the client was redirected to a given route. 
    * 
    * @param string $name 
    * @param array $parameters 
    * @param array $with 
    * @return void 
    */ 
    public function assertRedirectedToRoute($name, $parameters = array(), $with = array()) 
    { 
     $this->assertRedirectedTo($this->app['url']->route($name, $parameters), $with); 
    } 

리디렉션 외관이 Illuminate\Routing\Redirector으로, route() 메서드가 createRedirect()으로 호출되어 Illuminate\Http\RedirectResponse의 인스턴스를 반환하므로 문제가 될 수 있습니다.

UPDATE :

그냥 코드를 다시 확인하고 문제가 AssertionsTrait::assertRedirectedTo() 방법 내에있는 것 같습니다. $this->client->getResponse()을 호출하면 Illuminate\Http\RedirectResponse 대신 Illuminate\Http\Response 인스턴스가 반환되므로 $this->assertInstanceOf('Illuminate\Http\RedirectResponse', $response) 호출이 실패합니다. 그러나 나는 아직도 확신 할 수 없다 - 나는 모든 환경 설정 등을 돌 보려고하는 TestCase을 확장하고있다. 어떤 생각 일까?

+2

리소스로 작업한다고 가정하면 create 메소드에있는 논리는 실제로 store 메소드에 있어야합니다. posts/create는 데이터를 입력하기 위해 양식이있는 뷰를 반환해야하며, store 메소드는 입력 데이터를 가져 와서 실제로 객체를 만들고 저장합니다. 그래서'$ this-> post ('posts', $ input);는'create()'메소드가 아니라'store()'메소드를 호출합니다. 그래서 그것을 보아라. 그렇지 않다면 아마도 404 응답을 얻고있을 것이다. 이것은 리다이렉트가 아니다. – Quasdunk

+0

당신은 맞습니다. @ Quasdunk - 이것을 지적 해 주셔서 감사합니다. 수락 할 수 있도록 답으로 게시 할 수 있습니까? –

답변

1

답변으로 게시 코멘트 :

당신은 수완 객체와 협력하고 있기 때문에, Laravel가 자동으로 즉, 당신을 위해 몇 가지 경로를 작성합니다

+-----------------------------+---------------+-------------------------+ 
| URI       | Name   | Action     | 
+-----------------------------+---------------+-------------------------+ 
| GET|HEAD posts    | posts.index | [email protected] | 
| GET|HEAD posts/create  | posts.create | [email protected] | 
| POST posts     | posts.store | [email protected] | 
| GET|HEAD posts/{posts}  | posts.show | [email protected] | 
| GET|HEAD posts/{posts}/edit | posts.edit | [email protected] | 
| PUT posts/{posts}   | posts.update | [email protected] | 
| PATCH posts/{posts}   |    | [email protected] | 
| DELETE posts/{posts}  | posts.destroy | [email protected] | 
+-----------------------------+---------------+-------------------------+ 

당신이 볼 수 있듯이, POST 요청을 to/posts (테스트 에서처럼)는 테스트중인 것으로 가정 한 create() 메서드가 아니라 PostsController에서 store() 메서드를 트리거합니다.

createstore뿐만 아니라 editupdate 가끔 혼란 스러울 수 있습니다.여기에 차이점 :

  • create()가 - 새로운 자원
  • store()을 만들기위한 폼을 표시 - 실제로 게시 된 데이터

  • edit($id)에서 자원을 작성 -에 대한 폼을 표시 지정한 리소스 편집
  • update($id) - 실제로 리소스를 업데이트합니다. th 게시 된 데이터
+0

감사합니다. @Quasdunk. –

+0

@seb 매우 환영합니다 :) – Quasdunk