Laravel header 测试为空
Laravel header null on test
我正在基于帐户模型使用 Laravel 构建多租户 api,我通过使用特征确定请求 reader "Account" 使用的租户(AccountScoped)在所有租户模型上,一切都在邮递员上工作,但是为什么要测试 header 在特征中是不可访问的。
AccountScopped(特质)
trait AccountScoped
{
protected static function bootAccountScoped()
{
$account_id = request()->header('Account');
dd($account_id);
if (empty($account_id)) {
return;
}
static::creating(function (Model $model) use ($account_id) {
$model->account_id = $account_id;
});
static::addGlobalScope('byAccount', function (Builder $builder) use ($account_id) {
$builder->where('account_id', '=', $account_id);
});
}
}
测试方法:
public function testActionIndexInController()
{
$categories = Category::where('account_id',$this->account->id)->get()->toJSON();
$response = $this->actingAs($this->user, 'api')
->withHeader('Account',$this->account->id)
->get(route('categories.index'));
$response->assertStatus(200)->assertSee($categories);
}
* $this->user是一个带有Accounts的User实例模型,$this->account是一个与所选用户相关的Account实例
但是当我 运行 测试时,我在 $account_id 上得到空值
Test return
当我通过邮递员发出相同的请求时,值就在那里
Postman Return
如果您使用的是 jwt,则可以在测试模式下使用此代码设置请求
if (env('APP_ENV') === 'testing') {
JWTAuth::setRequest($request);
}
否则,您需要使用Illuminate\Http\Request设置请求;
此外,您可以尝试使用此代码获取 header
\Illuminate\Support\Facades\Request::instance()->headers->get('Account')
我正在基于帐户模型使用 Laravel 构建多租户 api,我通过使用特征确定请求 reader "Account" 使用的租户(AccountScoped)在所有租户模型上,一切都在邮递员上工作,但是为什么要测试 header 在特征中是不可访问的。
AccountScopped(特质)
trait AccountScoped
{
protected static function bootAccountScoped()
{
$account_id = request()->header('Account');
dd($account_id);
if (empty($account_id)) {
return;
}
static::creating(function (Model $model) use ($account_id) {
$model->account_id = $account_id;
});
static::addGlobalScope('byAccount', function (Builder $builder) use ($account_id) {
$builder->where('account_id', '=', $account_id);
});
}
}
测试方法:
public function testActionIndexInController()
{
$categories = Category::where('account_id',$this->account->id)->get()->toJSON();
$response = $this->actingAs($this->user, 'api')
->withHeader('Account',$this->account->id)
->get(route('categories.index'));
$response->assertStatus(200)->assertSee($categories);
}
* $this->user是一个带有Accounts的User实例模型,$this->account是一个与所选用户相关的Account实例
但是当我 运行 测试时,我在 $account_id 上得到空值 Test return
当我通过邮递员发出相同的请求时,值就在那里 Postman Return
如果您使用的是 jwt,则可以在测试模式下使用此代码设置请求
if (env('APP_ENV') === 'testing') {
JWTAuth::setRequest($request);
}
否则,您需要使用Illuminate\Http\Request设置请求; 此外,您可以尝试使用此代码获取 header
\Illuminate\Support\Facades\Request::instance()->headers->get('Account')