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 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看