Search code examples
seleniumphpunitsaucelabs

Dynamically setting the $browsers static property in Sauce.io phpunit selenium tests


I am setting up some browser testing using SauceLabs. I've been able to get tests running locally and via Sauce, so I am now trying to integrate it with my Jenkins install to trigger builds and browser tests automatically.

Most of this is all working, but I have one small issue. So that I can run my tests locally and via Sauce, I want to set the $browsers static property during the phpUnit setup() function, rather than hardcoding it. This doesn't seem possible.

I'm using the Sausage binding, my TestCase looks pretty similar to this demo: https://github.com/jlipps/sausage/blob/master/WebDriverDemo.php

I have tried in setUp() to update the $browsers array, but it never seems to take effect. eg.

public function setUp()
{   
    self::$browsers = array(
        'browserName' => getenv('SELENIUM_BROWSER'),
        'desiredCapabilities' => array(
            'version' => getenv('SELENIUM_VERSION'),
            'platform' => getenv('SELENIUM_PLATFORM'),
         )
     );
}

Is there a way to pass the browser details from Jenkins so the test cases are more flexible? I feel like I'm missing something simple here?


Solution

  • Ok, so I worked this out. Should anyone else have the same issue, here's how I resolved it.

    In the ANT script that Jenkins runs, which runs PHPUnit in turn, I included a config.xml file. This sets a config (environment) variable called sauce to true

    <phpunit> 
        <php>
            <env name="sauce" value="true" />
        </php>
    </phpunit>
    

    Now the trick is to not actually use the $browsers static array, but instead to use the setupSpecificBrowser method. So , now in my setUp() function of my tests, I just switch on the sauce env variable and if it exists then I know we are running from Jenkins and so I use the supplied variables from it.

        if( getenv('sauce') == true) {
            $browser =  array(
                    'browserName' => getenv('SELENIUM_BROWSER'),
                    'desiredCapabilities' => array(
                            'version' => getenv('SELENIUM_VERSION'),
                            'platform' => getenv('SELENIUM_PLATFORM'),
                    )
            );
        } else {
            $browser =  array(
                    'browserName' => 'firefox',
                    'local' => true,
                    'sessionStrategy' => 'isolated'
            );
        }
        $this->setupSpecificBrowser($browser);
    

    AFAIK there doesn't seem to be any documentation for this, I just worked it from from looking at the code. Fun.