我有下面的测试,在提交之前,我需要修改隐藏输入字段的值。
如何在提交之前更改隐藏的
_token字段?
public function it_fails_to_submit_aun_invalid_token_post()
{
// Given I am a not authenticated user (guest)
// And I visit the homepage
$this->visit('/auth/login');
// And I fill the login form
$this->type('test@example.org', 'email')
->type('password', 'password');
// TODO: HERE Change the _token field value to simulate invalidation/tampering
// Would be something similar to:
// $this->type('INVALID TOKEN', '_token');
// But this doesn't work because of (apparently) the DOM lib limitations inherited by TestCase
$this->click('Login');
// Then I should see an invalid token message
$this->see('please submit your form again');
}github项目在这里上的完整测试代码
有一个关于燕麦的类似讨论似乎还没有解决这个问题。
发布于 2015-12-04 13:15:39
我可以看到,您现在已经找到了使您的测试工作正常的解决方案。昨天我确实对此做了更多的思考,我认为试图改变隐藏字段的值的总体问题是,用户无法实际地更改该值,因此尝试模拟该值没有多大意义。我认为,在您的例子中,使用session()->regenerateToken();是最有意义的。
但是,在查看了失败的测试之后,我确实使用了call()方法,并为运行类似的测试提供了一种不同的方法:
$this->call('POST', 'auth/login', [
'email' => 'test@example.org',
'password' => 'password',
'_token' => 'foo'
]);
// Get the localhost so we can check the redirect
$localhost = 'http://'.request()->server('HTTP_HOST');
$this->assertRedirectedTo("{$localhost}/auth/login");
$this->assertSessionHasErrors(['token_mismatch' => 'please submit your form again']);在这里,我使用填充了相关字段的post方法发出了一个call()请求。然后,Laravel提供了assertRedirectedTo()和assertSessionHasErrors()方法,它们只是测试您被重定向到正确的位置,并且您的错误消息在会话中(我使用LaravelwithErrors()重定向回来)。
顺便说一句,如果您想检查错误消息是否实际显示,(而不仅仅是在会话中),您可以这样做:
$this->visit("/auth/login")
->see('Have you been away? Please try submitting the form again');来模拟重定向。
发布于 2015-12-03 17:09:16
我根据@Lee的建议,通过检查Laravel的测试,找到了编写测试的解决方案。
我添加了session()->regenerateToken();来模拟无效令牌。
尽管如此,这并不回答如何改变实际的隐藏字段,但是对于这个特殊的需求,它不再是必需的。
/**
* Regresion for https://github.com/alariva/timegrid/issues/39
* @test
*/
public function it_fails_to_submit_an_invalid_token_post()
{
// Given I am a not authenticated user (guest)
// And I visit the homepage
$this->visit('/auth/login');
// And I fill the login form
$this->type('test@example.org', 'email')
->type('password', 'password');
// And my session expired so as a token was invalidated
session()->regenerateToken();
// And I submit the form
$this->press('Login');
// Then I should see a message asking for resubmit
$this->see('please submit your form again');
}https://stackoverflow.com/questions/34067075
复制相似问题