doushan1863 2014-02-04 10:13
浏览 67
已采纳

Laravel控制器测试,处理重定向

I have a bit of an issue, the below code is from one of the methods within my controller that I'm testing.

The scenario is, you save a record and you're automatically directed to 'viewing' that record. So I am passing in the items id upon save to the redirect...

However, when running the tests I receive 'ErrorException: Trying to get property of non-object' if I pass in the id of the object straight off. So the work around I'm doing the pass the test is a ternary condition to see if the output is an object...surely there must be a better way of doing this?

I'm using Mockery, and have created a mock class/interface for the Projects model which is injected into the Projects main controller.

Here's the method:

public function store()
{
    // Required to use Laravels 'Input' class to catch the form data
    // This is because the mock tests don't pick up ordinary $_POST
    $project = $this->project->create(Input::only('projects'));

    if (count(Input::only('contributers')['contributers']) > 0) {
        $output = Contributer::insert(Input::only('contributers')['contributers']);
    }

    // Checking whether the output is an object, as tests fail as the object isn't instatiated
    // through the mock within the tests
    return Redirect::route('projects.show', (is_object($project)?$project->id:null))
                   ->with('fash', 'New project has been created');
}

And heres the test which is testing the redirected route.

       Input::replace($input = ['title' => 'Foo Title']);


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

    $this->call('POST', 'projects');

    $this->assertRedirectedToRoute('projects.show');
    $this->assertSessionHas('flash');
  • 写回答

1条回答 默认 最新

  • doudun1934 2014-02-04 11:07
    关注

    You have to define the response of your mock when the method create is called to properly simulate the real behavior :

    $mockProject = new StdClass; // or a new mock object
    $mockProject->id = 1;
    $this->mock->shouldReceive('create')->once()->andReturn($mockProject);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里