5

我正在 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属性,我没有问题。

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

4

2 回答 2

2

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

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

但是,Laravel 默认情况下不使用备用包,所以我假设您正在代码中做一些事情来App\Request::$errorBag向会话处理程序注册您的。

于 2015-07-25T13:39:13.127 回答
0

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

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

在您可以在会话中断言某些内容之前。请参阅 Laravel 5.0 的测试助手部分

于 2015-07-29T10:24:31.433 回答