【发布时间】:2014-01-24 15:55:46
【问题描述】:
我在 Laravel 测试中遇到了这种奇怪的行为。让我告诉你我的测试。
<?php
class MatchesControllerTest extends TestCase
{
public function setUp()
{
parent::setUp();
DB::beginTransaction();
}
public function tearDown()
{
DB::rollBack();
}
public function testForFun()
{
$title = 'Yay Great Post';
// "Create" post
Post::create(compact('title'));
$crawler = $this->client->request('GET', 'posts');
$this->assertEquals(
1,
count($crawler->filter("body:contains('{$title}')")),
"Expected to see the text '{$title}' within a body element."
);
}
}
现在理想情况下,测试应该创建一行并在测试结束后立即删除,但它没有发生,我应该做些什么。我知道当发生一些意外异常时会调用回滚,但我故意在最后调用它,这不应该像我们认为的那样工作吗?
【问题讨论】:
-
是否调用了
rollBack()方法?Post::create()不会调用它自己的commit()吗? -
我遇到了同样的问题。据我所知
::create()没有使用交易。即便如此,Laravel 也支持嵌套事务。 -
哦,这就是为什么它不能像我们预期的那样工作!
-
尝试调用 parent::tearDown();在tearDown方法上,在你回滚之前
-
@KbirMhrjn Post::create() 也将模型保存到数据库中。 create() 函数在 Illuminate\Database\Eloquent\Builder 中并调用
$instance->save();方法。
标签: php unit-testing laravel-4