【问题标题】:LARAVEL 5.0 + Unit Test - assertSessionHasErrors with different bagsLARAVEL 5.0 + 单元测试 - 不同包的 assertSessionHasErrors
【发布时间】:2015-10-09 23:09:22
【问题描述】:

我正在 Laravel 5.0 中编写单元测试,在我的请求类中我使用不同的包来显示验证错误消息。

我在我的文件中使用这个:

/* ExampleRequest.php */
namespace App\Http\Requests;

use App\Http\Requests\Request;
use Illuminate\Support\Facades\Auth;

class ExampleRequest extends Request {

    protected $errorBag = 'otherbag';

    public function rules(){
        return [
            'my_field' => 'required'
        ];
    }
}

在我的测试文件中,我正在使用这个进行测试:

/* ExampleTest.php */
class ExampleTest extends TestCase {
    public function testPostWithoutData(){
        $response = $this->call('POST', 'url/to/post',[
            'my_field' => ''
        ]);
        $this->assertSessionHasErrors('my_field');
    }
}

如果我运行测试,它无法获得正确的断言并返回此问题:

会话丢失错误:my_field 断言 falsetrue 失败。

如果我从请求文件中取出$errorBag属性,就没有问题了。

我可以根据需要提供更多详细信息。

【问题讨论】:

  • 你能解释一下为什么你的对象中有protected $errorBag = 'otherbag';吗?这是做什么的,为什么?
  • 因为我有两个地方可以展示我的观点......而且我用不同的袋子处理它......

标签: php unit-testing laravel-5 laravel-validation laravel-request


【解决方案1】:

您可以像这样从会话存储中获取备用包:

$myBag = $this->app('session_store')->getBag('otherBag');
$this->assertTrue($myBag->any());

但是,Laravel 默认不使用备用包,所以我假设您正在代码中执行某些操作以向会话处理程序注册您的 App\Request::$errorBag

【讨论】:

    【解决方案2】:

    我不知道您是否在其他地方设置会话,但我猜您可能会执行以下操作:

    $this->session(['foo' => 'bar']);

    在您可以在会话中断言某些内容之前。 See testing helpers section for Laravel 5.0

    【讨论】:

      猜你喜欢
      • 2016-10-01
      • 2021-11-23
      • 2017-07-05
      • 2019-08-01
      • 1970-01-01
      • 2018-09-15
      • 2021-12-03
      • 2017-12-05
      • 1970-01-01
      相关资源
      最近更新 更多