发布' AccountApiKey [merchant_id]'的正确语法是什么?在下面的示例中,用于测试Laravel 5.4中的插入。
在生产中,代码工作正常,没有任何问题,在测试中我得到错误"表未找到"没有正确插入的地方。我已经在IRC中问了但是它让我们难过,所以我希望精彩的stackoverflow社区可以提供帮助。
谢谢!
查看:
{{-- Merchant ID form input --}}
<div class="form-group">
{!! Form::label('AccountApiKey[merchant_id]', 'Seller ID:') !!}
{!! Form::text('AccountApiKey[merchant_id]', null, ['class' => 'form-control']) !!}
</div>
测试(参见下面的完整测试更新):
$accountApiKey = factory(AccountApiKey::class)->make([
'merchant_id' => 'test'
]);
$this->post($this->urlToUse(), [
'name' => $account->name,
'AccountApiKey[merchant_id]' => $accountApiKey->merchant_id,
]);
$this->assertDatabaseHas('account_api_keys', [
'merchant_id' => $accountApiKey->merchant_id,
]);
控制器:
$account->accountApiKey()->save(new AccountApiKey($request->get('AccountApiKey')));
按照Sandeesh评论更新:
型号:
class AccountApiKey extends Model implements Transformable
{
use TransformableTrait;
protected $fillable = ['last_modified_user_id', 'merchant_id'];
protected $events = ['saving' => SettingsUpdated::class];
public function account()
{
return $this->belongsTo('App\Models\Account\Settings\Accounts');
}
}
完成测试:
class StoreTest extends TestCase implements TestInterface
{
use DatabaseMigrations;
/**
* Tests all forms are inserting correct into database
*/
public function test_inserting_into_database()
{
$user1 = $this->userAndCompany();
$this->actingAs($user1);
$account = factory(Account::class)->create([
'company_id' => $user1->company()->first()->id,
]);
$accountApiKey = factory(Account\AccountApiKey::class)->make([
'last_modified_user' => $user1->id,
'account_id' => $account->id,
'merchant_id' => 'test'
]);
$this->post($this->urlToUse(), [
'name' => $account->name,
'AccountApiKey[merchant_id]' => $accountApiKey->merchant_id,
]);
$this->assertDatabaseHas('accounts', [
'name' => $account->name, //asserts true
]);
$this->assertDatabaseHas('account_api_keys', [
'merchant_id' => $accountApiKey->merchant_id, // asserts false
]);
}
/**
* The url which is under test
* @return mixed
*/
function urlToUse()
{
return 'account/settings/account';
}
}
答案 0 :(得分:1)
好的,我发现了这个问题,你必须将你的帖子数据更改为这个,以便测试工作。
$this->post($this->urlToUse(), [
'name' => $account->name,
'AccountApiKey' => [
'merchant_id' => $accountApiKey->merchant_id,
],
]);
与此同时,您不必要地使用可以使用普通输入的数组输入。如果你想,那么我会给你一些清理代码的建议。