我正在尝试熟悉 Geb .我正在尝试从 Grails 内部运行它,但这根本不重要,因为我的问题是针对 Geb 的。
我有以下 test
目录结构:
myapp/
<lots of stuff here>
test/
functional/
GebConfig.groovy
LogInLogOutSpec.groovy
pages/
LogInPage.groovy
DashboardPage.groovy
在哪里
LoginPage.groovy
是(显然)登录页面,DashboardPage
是您成功登录后应该被重定向到的地方。实际上,我有安全过滤器来检查您尝试访问的 URL 是否需要身份验证。如果是这样,他们会将您重定向到登录页面,并在成功登录后再次将您重定向到您尝试访问的 URL。为了更好地衡量,这是构成我的登录页面的 HTML(同样,这是 Grails,因此 GSP 文件会在运行时动态转换为 HTML):
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<form action=“/myapp/auth/signIn" method="post">
<input type="hidden" name="targetUri" value="/dashboard" />
<table>
<tbody>
<tr>
<td>Username:</td>
<td><input type="text" name="username" value="" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" value="" /></td>
</tr>
<tr>
<td />
<td><input type="submit" value="Sign in" /></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
所以我需要一个 Geb 测试:
此外:
HtmlUnitDriver
,但如果我是,请纠正我错误)GebConfig
注入(inject)。文件或一些外部参数(可能作为提供给 Grails 命令行的环境变量或运行时参数)。本质上我不想在测试代码中存储用户名/密码。 到目前为止我最好的尝试:
GebConfig.groovy
:driver = {
// Again, or Firefox
ChromeProfile profile = new ChromeProfile()
Driver driverInstance = new ChromeDriver(profile)
driverInstace.manage().window().maximize()
driverInstance
}
baseNavigatorWaiting = true
atCheckWaiting = true
// Need to inject from some external process somehow, but make these
// available to test specs somehow.
username = System.env("USERNAME")
password = System.env("PASSWORD")
LogInLogOutSpec.groovy
:import geb.spock.GerbReportingSpec
import spock.lang.*
import pages.*
@Stepwise
class LogInLogOutSpec extends GebReportingSpec {
String username
String password
/*
* Attempt to go to user dashboard, and confirm you are instead
* redirected to the login page. Login with good credentials,
* and verify you are now logged in and at the dashboard.
*/
def "successful login redirects to dashboard page"() {
when:
to DashboardPage
then:
"Login".equals($(".page-header").text())
when:
$("#login-form input[name=username]").value(username)
$("#login-form input[name=password]").value(password)
then:
"Dashboard".equals($(".page-header").text())
}
}
我想我已经接近了,但这显然是错误的。有什么想法我会出错吗?谢谢!
最佳答案
您应该模块化您的测试代码。你应该使用
在您的代码示例中,您有一个仪表板页面,但没有登录页面对象。如果您的所有页面都可以登录或至少提供检测登录状态的可能性,您还应该考虑登录模块。看到这个SO answer对于模块定义。这里缺少的是一个确定登录状态的函数。有关另一个实现,请查看 AuthModule和 login test spec的Geb examples .
对于登录凭据:我认为您在环境中拥有凭据做得很好。这在开发人员机器和构建服务器上都可以正常工作。
使用不同浏览器进行测试:geb-example-gradle是一个带有 GebConfig 的 gradle 示例项目和 build.gradle .这允许您将浏览器作为参数切换到 gradle:
./gradlew chromeTest
./gradlew firefoxTest
./gradlew phantomJsTest
这也回答了你的最后一个问题:我喜欢使用的一个好的 headless 浏览器是 phantomJs .
关于grails - Geb 登录规范示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33044117/