首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何改变TestCase 5中的隐藏字段?

如何改变TestCase 5中的隐藏字段?
EN

Stack Overflow用户
提问于 2015-12-03 13:17:06
回答 2查看 1.2K关注 0票数 1

我有下面的测试,在提交之前,我需要修改隐藏输入字段的值。

如何在提交之前更改隐藏的_token字段?

代码语言:javascript
复制
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项目在这里上的完整测试代码

有一个关于燕麦的类似讨论似乎还没有解决这个问题。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-12-04 13:15:39

我可以看到,您现在已经找到了使您的测试工作正常的解决方案。昨天我确实对此做了更多的思考,我认为试图改变隐藏字段的值的总体问题是,用户无法实际地更改该值,因此尝试模拟该值没有多大意义。我认为,在您的例子中,使用session()->regenerateToken();是最有意义的。

但是,在查看了失败的测试之后,我确实使用了call()方法,并为运行类似的测试提供了一种不同的方法:

代码语言:javascript
复制
$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()重定向回来)。

顺便说一句,如果您想检查错误消息是否实际显示,(而不仅仅是在会话中),您可以这样做:

代码语言:javascript
复制
$this->visit("/auth/login")
            ->see('Have you been away? Please try submitting the form again');

来模拟重定向。

票数 1
EN

Stack Overflow用户

发布于 2015-12-03 17:09:16

我根据@Lee的建议,通过检查Laravel的测试,找到了编写测试的解决方案。

我添加了session()->regenerateToken();来模拟无效令牌。

尽管如此,这并不回答如何改变实际的隐藏字段,但是对于这个特殊的需求,它不再是必需的。

代码语言:javascript
复制
/**
* 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');
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34067075

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档