我试图在Laravel 4中的数据库播种期间关联相关模型.根据这里的文档,我可以这样做:
$user->roles()->attach(1);
Run Code Online (Sandbox Code Playgroud)
所以,在我正在运行的数据库种子中:
$package = Package::create([
'name' => $faker->word,
'summary' => $faker->sentence,
'base_price' => $faker->randomFloat(2, 200, 10000)
]);
// Attach 1-5 randomly selected items to this package
foreach(range(1, 5) as $index)
{
$randomItem = Item::orderBy(DB::raw('RAND()'))->first();
$package->items()->attach($randomItem->id);
}
Run Code Online (Sandbox Code Playgroud)
包装物品此时已经播种,并且种子没有问题.上面的代码从Artisan给出了这个:
[BadMethodCallException]
Call to undefined method Illuminate\Database\Query\Builder::attach()
Run Code Online (Sandbox Code Playgroud)
这里的某个人似乎认为该attach()
方法实际上并不存在且文档错误,但我发现很难相信.
TL; DR在Eloquent中创建多对多关系的正确方法是什么?
我在使用Laravel的Input::replace()
方法在单元测试期间模拟POST请求时遇到了一些麻烦.
根据Jeffrey Way 这里和这里的说法,你可以这样做:
# app/tests/controllers/PostsControllerTest.php
public function testStore()
{
Input::replace($input = ['title' => 'My Title']);</p>
$this->mock
->shouldReceive('create')
->once()
->with($input);
$this->app->instance('Post', $this->mock);
$this->call('POST', 'posts');
$this->assertRedirectedToRoute('posts.index');
}
Run Code Online (Sandbox Code Playgroud)
但是,我不能让这个工作.Input::all()
并且所有Input::get()
调用仍然返回一个空数组或Input::replace()
使用后返回null .
这是我的测试功能:
public function test_invalid_login()
{
// Make login attempt with invalid credentials
Input::replace($input = [
'email' => 'bad@email.com',
'password' => 'badpassword',
'remember' => true
]);
$this->mock->shouldReceive('logAttempt')
->once()
->with($input)
->andReturn(false);
$this->action('POST', 'SessionsController@postLogin');
// Should redirect back to login form with old input …
Run Code Online (Sandbox Code Playgroud) 我试图在单元测试中模拟Laravel的一些外观,但似乎测试总是通过无论如何.
例如,此示例取自Laravel文档:
Event::shouldReceive('fire')->once()->with('foo', array('name' => 'Dayle'));
Run Code Online (Sandbox Code Playgroud)
看起来我可以把它放在任何一种测试方法中,即使在Event
外观上没有做过任何类型的测试,它们总是会通过.
这是测试类:
class SessionsControllerTest
extends TestCase
{
public function test_invalid_login_returns_to_login_page()
{
// All of these pass even when they should fail
Notification::shouldReceive('error')->once()->with('Incorrect email or password.');
Event::shouldReceive('fire')->once()->with('foo', array('name' => 'Dayle'));
Notification::shouldReceive('nonsense')->once()->with('nonsense');
// Make login attempt with bad credentials
$this->post(action('SessionsController@postLogin'), [
'inputEmail' => 'bademail@example.com',
'inputPassword' => 'badpassword'
]);
// Should redirect back to login form with old input
$this->assertHasOldInput();
$this->assertRedirectedToAction('SessionsController@getLogin');
}
}
Run Code Online (Sandbox Code Playgroud)
我为了测试外墙而缺少什么?我是否正确地认为我应该可以shouldReceive()
在没有任何设置的情况下调用任何Laravel Facade?