A minimal WebDriver based DSL

I read on the Wikipedia entry for Selenium, that Selenium 2.0 aims to provide a base for your own DSL (Domain Specific Language).

“What might such a language look like?” I thought to myself.

Well, I’ve build DSLs before, but I really thought “What might the minimal DSL that I could create look like?”

And so, we proudly present. The FluentWebElement.

Yes, all you Seleniumists and Webdriverites, now you too can write:

myWeblement.clear().and().sendKeys(“woo, a new dawn”).then().submit();

OK, so you’d have to write a bit more. Let me list the full test:

private static WebDriver driver;

@BeforeClass
public static void setup(){
    driver = new FirefoxDriver();
    driver.get("http://www.compendiumdev.co.uk/selenium/search.php");
}

@Test
public void whatIfWeHadAFluentWebElementForSearchPage(){

 FluentWebElement searchBox = new FluentWebElement(driver.findElement(By.name("q")));

 searchBox.clear().then().sendKeys("Fluent Programming").and().submit();

 assertTrue(driver.getTitle().contains("Fluent Programming"));
}

@AfterClass
public static void tearDown(){
    driver.quit();
}

And how was this done?

If you look in the source code repository then you can see the test, and the FluentWebElement code.

Just a class that wraps the WebElement, delegating off to the WebElement most of the time and returning self, for all those WebElement methods that normally void out.

e.g. the important bits

    private WebElement webElement;

    public FluentWebElement(WebElement aWebElement){
        this.webElement = aWebElement;

    }

    // Fluentese
    public FluentWebElement click() {
        webElement.click();
        return this;
    }

    public void submit() {
        webElement.submit();
    }

    public FluentWebElement sendKeys(CharSequence... keysToSend) {
        webElement.sendKeys(keysToSend);
        return this;
    }

    public FluentWebElement clear() {
        webElement.clear();
        return this;
    }

    public FluentWebElement and(){
        return this;
    }

    public FluentWebElement then(){
        return this;
    }

Warning: This has not been used in a production environment. This was a “What If?”, fun experiment.

This entry was posted in Selenium Simplified Blog, WebDriver. Bookmark the permalink.

One Response to A minimal WebDriver based DSL

  1. Pingback: A Smattering of Selenium #108 « Official Selenium Blog

Leave a Reply

Your email address will not be published. Required fields are marked *