How to verify error messages using Geb - selenium

How do i capture the error messages generated on web page(for example an error message generated when a login button is pressed without inserting any username or password), how do i extract this error message "Username is required" using geb.
im using geb groovy based automation

So you would first model your page, and get the locator for the error you want to assert has been displayed. Note that you want to set this to required: false as you would not expect it to be displayed when you first land on the page.
Page with example page error with ID of #pageError:
class MyPage extends Page
{
static url = "/mypageurl"
static at = {
title == "My Page"
}
static content = {
pageError (required: false) { $('#pageError') }
submitButton { $('#mySubmitButton') }
}
def submitForm() {
submitButton.click()
}
}
Then you have your test:
def "If I try click Submit without filling out all form details show me an error message"()
{
when: "I click Submit without completing all form fields"
def myPage = to(MyPage)
myPage.submitForm()
then: "I am shown an error message on the same page"
myPage.pageError.displayed
}
EDIT:
Noticed you mentioned getting the content of the error, you would call this instead to get the text:
myPage.pageError.text()

Related

When I am trying to send amount data to user dashboard directly by using auth middleware, then getting error "Attempt to read property "name" on null"

I am trying to send product details to user dashboard, if user is login then it should directly show on dashboard and if not then it should be ask for register then on same popup he can edit the amount and pay on next click.
I am trying to send using session however getting error.
Attempt to read property "name" on null
public function addToCart(About $about)
{
if (Auth::check()) {
if(session()->has('cart'))
{
$cart = new Account(session()->get('cart'));
}
else{
$cart= new Account();
}
$cart->add($about);
//dd($cart);
session()->put('cart', $cart);
//return redirect()->back();
return view('amount', compact('cart'));
}}

How to change the database if printed?

I have a button that prints
<input type = "button" onclick = "printDiv ('printableArea')" class = "button1" value = "Print" />
<script>
function printDiv (divName) {
var printContents = document.getElementById (divName) .innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print ();
document.body.innerHTML = originalContents;
}
</script>
And it sends to print operation.
The customer currently has the option to print or cancel.
Is there a way to access code behind in case the customer presses a print button?
(I want to change in my database that the client has already printed ...)
Regards
Is there a way to access code behind in case the customer presses a print button?
Please note that we can not directly detect if user clicked the 'Print' or 'Cancel' button in printing dialog via JS code from a html page.
Similar issue discussed in this SO thread: How to capture the click event on the default print menu called by Javascript window.print()?
As a workaround, you can try to show a prompt dialog to confirm if the printing is complete and then make request to backend to update database once the afterprint event is raised, like below.
window.onafterprint = function () {
var message = "Have you printed the page(s)?";
var result = window.prompt(message,"yes");
if (result=="yes") {
//...
//make ajax request to backend
//...
}
};
You can add a GET request to an MVC Action like (in jQuery):
...
document.body.innerHTML = printContents;
var clientId = $("#clientId").val();
$.get("#Url.Action("SavePrinted", "Client")", { clientId: clientId });
window.print();
...

Intellij : Geb page object pattern navigation

While developing Geb script in IntelliJ it's very hard to navigate to page object method, So every time it required to open that page and serach for method.
For example:
Class LoginPage extends Page {
static at = { waitFor("slow") { title == "Login Page" }}
static content = {
txtUsername {$("#txtUserName")}
txtPassword {$("#pwd")}
btnLogin (required:false) {$("#Login")}
}
def login(String userName, String pwd){
// ...
}
}
class LoginSpec extends GebSpec {
def "verify logic scenario" {
given: 'Username and Password'
def username = "abc"
def password = "jdaafafjadfgajffaghfg"
when: 'Fire Login URL'
to LoginPage
and: 'Enter Valid username,password and click on Login button'
login(username, password)
then: 'It should successfully and redirect to homepage'
at HomePage
}
// ...
}
Here it's not easy to navigate to login method with one click.
Do we have any plugin or setting to make easy this navigation?
You can place the cursor on the page class name and just press Ctrl-B or use Ctrl-LeftMouse in order to get there. As for easier navigation and code completion, I suggest assigning the result of to MyPage to a variable and then use that variable for calling page methods, e.g.
class LoginSpec extends GebSpec {
def "verify logic scenario" {
given: "user name and password"
def username = "abc"
def password = "jdaafafjadfgajffaghfg"
when: "opening login page"
def loginPage = to LoginPage
and: "logging it with valid credentials"
loginPage.login(username, password)
then: "after successful login the user gets redirected to the homepage"
at HomePage
}
}
Now Ctrl-B and Ctrl-LeftMouse should also work for your method calls and page element references such as loginPage.txtUsername.

MVC 4 website back press return the same form with old values

I am new in MVC 4 web development and i am creating a control panel. I have developed a Add user page and submit information in database successfully.
But after submit when i press back button it will show previous form.
i am using redirection the page to same page after submit form.
here is the code to redirect
public ActionResult AdminPanel(RegisterUserModel user)
{
if (ModelState.IsValid) // Check the model state for any validation errors
{
if (user.AddUserToDB(user.username, user.password, user.fullName,user.contactNo,user.COAId)) // Calls the Login class checkUser() for existence of the user in the database.
{
TempData["SuccessMessage"] = "User Added Sucessfully!";
ModelState.Clear();
return Redirect("AdminPanel");
}
else
{
ViewBag.SuccessMessage = "User Not Added";
return View();
}
}
SelectList clientsList = GetClinetList();
ViewBag.clientsList = clientsList;
return View(); // Return the same view with validation errors.
}
I have tried many examples but issue not resolved yet so kindly give my suggesstions
If you don't want the user to be able to see the previous content when clicking back, then you must indicate that content should not be cached by the browser and must revalidate with the origin server
A summary of this behaviour is here - http://blog.55minutes.com/2011/10/how-to-defeat-the-browser-back-button-cache/
You could create a nocache attribute, like this one - https://stackoverflow.com/a/10011896/1538039, and apply it to your controller methods.

MVC page to page redirection

I'm new to MVC (using 4, framework 4.0) and I understand the basics but this page redirect isn't working as I expect. The application is a login/authentication which if the user successfully logs in it redirects them to the target application. That part works just fine. However the user may forget his/her login credentials, so I have a series of pages that will prompt the user for a registered email address and decoded captcha value. If that information is validated then another page prompts for a series of (up to 3) pre-determined security question answers (in the case of a password forgotten). If the security challenge question is successfully answered the user is redirected to a password change page. At any point in the process the user may click a cancel button which should redirect back to the login page and clear any state variables tracking their progress through the recovery process. The problem is I keep getting stuck on pages that even after a RedirectToAction("SomeAction", "SomeController"); I still stay on the page? The URI even changes on the browser but the page asking for email address or security question stays active. I'm using an ajax $.get() to call various actions for submit and cancel.
view is defined like this:
#using (Html.BeginForm("RecoverUserCredentialsByModel", "Account", FormMethod.Get, new { id = "form1" }))
{
<!--... three input controls and a submit and cancel button-->
<p>
<button id="btnSubmit" onclick="return CheckUserEmail()">Submit</button>
<button id="btnCancel" onclick="return CancelRecovery()">Cancel</button>
</p>
}
<script type="text/javascript">
function CheckUserEmail() {
var emailAddress = document.getElementById("EmailAddress").value;
var pictogramHref = document.getElementById("pictogramHref").src;
var pictogramAnswer = document.getElementById("Pictogram").value;
if (emailAddress != null) {
var url = "/Account/ValidateEmail";
$.get(url, { "emailAddress": emailAddress, "pictogramHref": pictogramHref, "pictogramTranslation": pictogramAnswer }, null);
return true;
}
}
</script>
<script type="text/javascript">
function CancelRecovery() {
var url = "/AuthenticationModule/Account/CancelRecovery";
$.get(url, {}, null);
return true;
}
</script>
Codebehind redirections look like:
/// <summary>
/// Global cancel recovery, clears the stateful session object and redirects back to login view
/// </summary>
/// <returns>ActionResult</returns>
[AllowAnonymous]
public ActionResult CancelRecovery()
{
LoginModel statefulLoginModel = null;
try
{
// Reset everything active and redirect to login view
statefulLoginModel = new LoginModel();
Session["LoginModel"] = statefulLoginModel;
return Redirector(statefulLoginModel);
}
catch (Exception ex)
{
// Log the error and Reset everything active and redirect to login view
FileLogger.Log(ex);
statefulLoginModel = new LoginModel();
Session["LoginModel"] = statefulLoginModel;
return Redirector(statefulLoginModel);
}
}
[AllowAnonymous]
public ActionResult Redirector(LoginModel model)
{
... some code
Session["LoginModel"] = statefulLoginModel;
if (loginState == 0)
{
RedirectToAction("LogOn");
}
}
When it hits the RedirectToAction("LogOn"); the view "RecoverUserInfo" stays active on the browser and no redirection occurs?
What am I doing wrong?
Try this..........
Proper Syntax is return RedirectToAction("ActionName","ControllerName");
In this case if Logon Action is written on the same Controller Then use following Code..
return RedirectToAction("LogOn");
or it is written on another controller then just replace your Action Name and Controller Name in the following code.
return RedirectToAction("ActionName","ControllerName");