GithubHelp home page GithubHelp logo

laracasts / integrated Goto Github PK

View Code? Open in Web Editor NEW
475.0 22.0 88.0 173 KB

Simple, intuitive integration testing with PHPUnit.

Home Page: https://laracasts.com/series/intuitive-integration-testing

License: MIT License

Shell 0.45% PHP 99.55%

integrated's Introduction

integrated's People

Contributors

alfredbez avatar bbloom avatar bmitch avatar butochnikov avatar bvangraafeiland avatar danielboendergaard avatar danwall avatar dwickstrom avatar edrands avatar ehkasper avatar flambe avatar grahamcampbell avatar jeffreyway avatar jildertmiedema avatar joecohens avatar kdocki avatar oxyzero avatar ozankurt avatar tamtamchik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

integrated's Issues

Problem creating helper methods

I'm having problems following this part: Can I create my own helper methods

1) DashboardTest::it_visits_the_dashboard
ErrorException: Undefined property: DashboardTest::$response

F:\Repositories\adriatica-admin\vendor\laracasts\integrated\src\Extensions\Laravel.php:84
F:\Repositories\adriatica-admin\vendor\laracasts\integrated\src\Extensions\Laravel.php:65
F:\Repositories\adriatica-admin\vendor\laracasts\integrated\src\Extensions\IntegrationTrait.php:74
F:\Repositories\adriatica-admin\app\tests\DashboardTest.php:17
F:\Repositories\adriatica-admin\app\tests\DashboardTest.php:12

This is my test:

<?php

use Laracasts\Integrated\Services\Laravel\DatabaseTransactions;

class DashboardTest extends TestCase {

    use DatabaseTransactions;

    /** @test */
    public function it_visits_the_dashboard()
    {
        $this->login();
    }

    protected function login($email = '[email protected]', $password = 'password') {

        return $this->visit('/login')
            ->submitForm('Prijava', ['email' => $email, 'password' => $password]);
    }

}

This is my TestCase class:

<?php

use Laracasts\Integrated\Extensions\Laravel as IntegrationTest;

class TestCase extends IntegrationTest {

    /**
     * Creates the application.
     *
     * @return Symfony\Component\HttpKernel\HttpKernelInterface
     */
    public function createApplication()
    {
        $unitTesting = true;

        $testEnvironment = 'testing';

        return require __DIR__.'/../../bootstrap/start.php';
    }

}

I am using version 0.12.0

Working with Multiple Value Checkboxes

Extending an issue I've brought up on the Laracasts Forums, I can't find the documentation or a method (if there is one) to submit data using the submitForm() method for multiple option checkboxes.

I've been told their may be a way to do this with Selenium; but as I won't be using Selenium for anything else, and that this functionality shouldn't require Selenium anyway, it seems like overkill.

An example without TestDummy:

<?php

use Laracasts\Integrated\Services\Laravel\DatabaseTransactions;

class WidgetTest extends TestCase {

    use DatabaseTransactions;

    /** @test */
    function it_can_create_a_widget() {
        $attributes = [
            'name' => 'Dummy Widget',
            'track' => [ 1 ]
        ];

        $this->visit('/widget')
             ->click('Create a Widget')
             ->onPage('/widget/create')
             ->submitForm('Create Widget', $attributes)
             ->andSee('You have created a new Widget!')
             ->onPage('/widget');
    }

}

When not using TestDummy (The example above) it doesn't error due to an unreachable field, like the example with TestDummy, it just doesn't check any of them.

And also with TestDummy:

<?php

use Laracasts\Integrated\Services\Laravel\DatabaseTransactions;
use Laracasts\TestDummy\Factory as TestDummy;

class WidgetTest extends TestCase {

    use DatabaseTransactions;

    /** @test */
    function it_can_create_a_widget() {
        $this->visit('/widget')
             ->click('Create a Widget')
             ->onPage('/widget/create')
             ->submitForm('Create Widget', TestDummy::attributesFor('App\Widget'))
             ->andSee('You have created a new Widget!')
             ->onPage('/widget');
    }

}

Factory (The various methods I've tried):

// None of these seem to work
$factory('App\Widget', [
    'track' => 0,
    'track[]' => 0,
    'track' => [ 0 ],
    'track[]' => [ 0 ],
]);

And the HTML:

<input name="track[]" type="checkbox" value="0">
<input name="track[]" type="checkbox" value="1">
<input name="track[]" type="checkbox" value="2">
<input name="track[]" type="checkbox" value="3">

The tests fail and the output shows that the track checkboxes are not being checked when specified.

seeJsonContains() does not "assert"

I had failing tests, made them pass but the end result is OK (2 tests, 1 assertion),

seeJsonContains fails properly, but doesn't increment the assertion count.

<?php

class UserTest extends TestCase
{
    public function setUp()
    {
        parent::setUp();
        $this->artisan('migrate');
        $this->seed('UserTableSeeder');
    }

    public function test_should_have_active_endpoint()
    {
        $this->get('/users/1')->seeStatusCode(200);
    }

    public function test_should_return_user_by_id()
    {
        $this->get('/users/1')->seeJsonContains(['id' => '1']);
    }
}

Noticed that the assertTrue() was replaced in a recent re-factoring with $this->fail()

Fatal error using Integrated w/ --testdox flag

Using Integrated with PHPUnit --testdox attribute throws following error

$ phpunit --testdox tests

Fatal error: Cannot use object of type Laracasts\Integrated\AnnotationReader as array in /Users/mikee/Documents/Projects/api-lumen/vendor/phpunit/phpunit/src/Util/TestDox/ResultPrinter.php on line 234

DatabaseTransactions not using correct .env file

When using DatabaseTransactions trait, it is using the .env file regardless of the existence of .env.testing, thus all tests are actually using the production database.

Surely I can change the value in .env during testing, but that would defeat the purpose.

Here is a screenshot of the execution, echoing the environment value

http://d.pr/i/1eCpx

Interface Methods

Hi,

When I do the following:

use Laracasts\Integrated\Extensions\Laravel as IntegrationTest;

class ExampleTest extends IntegrationTest {}

It wants me to implement the following methods: follow, check, tick, select, dump

Is that correct? or should one just ignore them?

Thanks!

This is puzzling...

I am receiving the following error when running a sample test

Fatal error: Class IntegrateTest contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Illuminate\Foundation\Testing\TestCase::createApplication) in /Users/mikee/Documents/Projects/rangladex5/tests/IntegrateTest.php on line 6

Call Stack:
    0.0005     248864   1. {main}() /Users/mikee/Documents/Projects/rangladex5/vendor/phpunit/phpunit/phpunit:0
    0.0446    2255168   2. PHPUnit_TextUI_Command::main() /Users/mikee/Documents/Projects/rangladex5/vendor/phpunit/phpunit/phpunit:36
    0.0446    2255792   3. PHPUnit_TextUI_Command->run() /Users/mikee/Documents/Projects/rangladex5/vendor/phpunit/phpunit/src/TextUI/Command.php:105
    0.0623    3204536   4. PHPUnit_Runner_BaseTestRunner->getTest() /Users/mikee/Documents/Projects/rangladex5/vendor/phpunit/phpunit/src/TextUI/Command.php:127
    0.0623    3204584   5. PHPUnit_Runner_BaseTestRunner->loadSuiteClass() /Users/mikee/Documents/Projects/rangladex5/vendor/phpunit/phpunit/src/Runner/BaseTestRunner.php:72
    0.0629    3230448   6. PHPUnit_Runner_StandardTestSuiteLoader->load() /Users/mikee/Documents/Projects/rangladex5/vendor/phpunit/phpunit/src/Runner/BaseTestRunner.php:127
    0.0631    3263912   7. PHPUnit_Util_Fileloader::checkAndLoad() /Users/mikee/Documents/Projects/rangladex5/vendor/phpunit/phpunit/src/Runner/StandardTestSuiteLoader.php:43
    0.0631    3264048   8. PHPUnit_Util_Fileloader::load() /Users/mikee/Documents/Projects/rangladex5/vendor/phpunit/phpunit/src/Util/Fileloader.php:42
    0.0632    3268088   9. include_once('/Users/mikee/Documents/Projects/rangladex5/tests/IntegrateTest.php') /Users/mikee/Documents/Projects/rangladex5/vendor/phpunit/phpunit/src/Util/Fileloader.php:58

Here is the test

visit('/');
    }

}

using POST or PUT, is the data json_encoded and what headers are sent?

My api accepts json and returns json...

When I was just using phpunit and Laravel's TestCase I would include the headers and json encoded data with $this->call().

Before Integrated (passing):

    protected $headers = [
        'CONTENT_TYPE' => 'application/json',
        'HTTP_ACCEPT'  => 'application/json',
    ];


    /** @test */
    public function it_adds_a_contact()
    {
        $data = [
            'email'  => '[email protected]',
            'attach' => [
                'tags'  => [1, 2, 3],
                'forms' => [2],
            ],
        ];
        $response = $this->call('POST', 'api/contacts', [], [], [], $this->headers, json_encode($data));
        $content = json_decode($response->getContent());
        $addedContact = SevenShores\Kraken\Contact::where('email', $data['email'])->first();
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals($data['email'], $content->email);
        $this->assertEquals(3, $addedContact->tags->count());
        $this->assertEquals(2, $addedContact->forms->first()->id);

Now with Integrated (failing):

    /** @test */
    public function it_adds_a_contact()
    {
        $data = [
            'email'  => '[email protected]',
            'attach' => [
                'tags'  => [1, 2, 3],
                'forms' => [2],
            ],
        ];

        $this->post('/api/contacts', $data)
             ->seeStatusCodeIs(200)
             ->seeJsonContains(['email' => '[email protected]'])
             ->seeInDatabase('contacts', $data);
    }

I am failing all my POST and PUT tests now, that I switched to laracasts/Integrated and just trying to figure out why.

FatalErrorException when submitting a form.

I get 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Call to undefined method ErrorException::getStatusCode()' when I try to submit a form why?

This is my code:

$this->visit('login')
->type('david', 'loginUsername')
->type('password', 'loginpassword')
->press('Login')
->see('You have logged in.');

Verify checkbox is checked

It would be awesome if it was possible to easily check whether a checkbox is checked. Could be via. a method called seeIsChecked or verifyIsChecked.

Real world example:
Settings page, where a user can check multiple checkboxes, and after submitting the form, you would need to verify that the checkboxes are now checked. As of now, you could only verify that the settings are stored in the database, but not that they are visually presented to the user.

Laravel exntesion not working

Followed installation instruction. Trying to use code below:

run() D:\www\laravel-dmca\vendor\phpunit\phpunit\src\TextUI\Command.php:105 0.0270 1739000 4. PHPUnit_TextUI_Command->handleArguments() D:\www\laravel-dmca\vendor\phpunit\phpunit\src\TextUI\Command.php:115 0.0370 2348672 5. PHPUnit_Util_Configuration->getTestSuiteConfiguration() D:\www\laravel-dmca\vendor\phpunit\phpunit\src\TextUI\Command.php:670 0.0370 2349920 6. PHPUnit_Util_Configuration->getTestSuite() D:\www\laravel-dmca\vendor\phpunit\phpunit\src\Util\Configuration.php:853 0.0530 2587904 7. PHPUnit_Framework_TestSuite->addTestFiles() D:\www\laravel-dmca\vendor\phpunit\phpunit\src\Util\Configuration.php:940 0.0530 2588728 8. PHPUnit_Framework_TestSuite->addTestFile() D:\www\laravel-dmca\vendor\phpunit\phpunit\src\Framework\TestSuite.php:405 0.0530 2620840 9. PHPUnit_Util_Fileloader::checkAndLoad() D:\www\laravel-dmca\vendor\phpunit\phpunit\src\Framework\TestSuite.php:333 0.0540 2620968 10. PHPUnit_Util_Fileloader::load() D:\www\laravel-dmca\vendor\phpunit\phpunit\src\Util\Fileloader.php:42 0.0550 2623448 11. include_once('D:\www\laravel-dmca\tests\ExampleTest.php') D:\www\laravel-dmca\vendor\phpunit\phpunit\src\Util\Fileloader.php:58 Goutte extension seems working...

More Form Helpers

Need to add other form helpers, in addition to "type" and "tick".

Things like:

  • check/tick
  • choose/select

What else?

Basic Auth

Hi @JeffreyWay - Thanks for the package - loving converting our existing tests over to the package!

Is there anyway to test an API via Basic Auth for a Laravel Project; I originally thought about settings a baseURL to include the User/Pass, however this doesn't seem to have worked.

I also need to set the Content-Type and Accepts header when making the request.

If not I can just use curl requests to test as we currently do - just trying to see if I can unify everything

How do I delete/clear a text input

I am trying to run a couple of Selenium tests and want to use the same session for all the tests to save time from opening a browser each time. However, I am not able to find a way to clear the text inputs that I am filling.

Example code:

$this->visit('login')
->see('Login')
->type('abc!@!', 'email')
->press('Login')
->see('Please enter a valid email');

$this->type('[email protected]')->press('Login')->see('Success');

However, this just appends to the previous input.

Essentially is there an equivalent command of sendKeys or like pressing "Delete" / "Backspace" on the input. The example above might not really reflect why I want to do "delete" but there are certain js outputs that I need to confirm only on a "Delete"/"Backspace" of an input.

Latest version has seemingly "broken" POST?

I version 0.14 I was able to have a complete suite of API tests passing with Lumen.

However, with the 0.14.1 update, all my POST tests are failing (they are not passing the data to the controller for further processing?

Has anybody experienced this issue?

The test is as follows:

/** @test */ public function it_should_create_batter() { $data = $this->getSeedData(); $this->post('/api/v1/batters', $data) ->seeJsonContains(['message' => 'Batter Created Successfully']); }

In the controller, I am retrieving as

// POST /batters public function store() { return $this->api_create($this->model, $this->request->input()); }

but the results from $this->request->input() are blank (empty array)

Any clues?

File upload

Is there a possibility to add the functionality to test file uploads? Testing where the file is moved to and such?

seeJsonContains() does not return reference to object anymore

Hi Jeffrey,

I found that on version 0.15.4 of Integrated, the "seeJsonContains()" method was refactored and does not return the reference to the object anymore:
https://github.com/laracasts/Integrated/blob/0.15.4/src/Extensions/Traits/ApiRequests.php#L182

The problem is that it breaks some tests which were relying on chain method calling. It's no big deal though, but I think that the problem should be fixed by simply returning $this at the end of the method.

Thanks for the module btw!

Receiving error when returning a 404 page w/ JSON result

I have a response of

{"error":{"message":"Resource Not Found","status_code":404}}

which produces the following error

Time: 5.05 seconds, Memory: 20.75Mb

There was 1 error:

  1. BatterTest::it_should_show_return_error_on_bad_request
    InvalidArgumentException: The current node list is empty.

/home/vagrant/code/rangladex5/vendor/symfony/dom-crawler/Symfony/Component/DomCrawler/Crawler.php:580
/home/vagrant/code/rangladex5/vendor/laracasts/integrated/src/Extensions/Laravel.php:152
/home/vagrant/code/rangladex5/vendor/laracasts/integrated/src/Extensions/IntegrationTrait.php:365
/home/vagrant/code/rangladex5/vendor/laracasts/integrated/src/Extensions/Laravel.php:65
/home/vagrant/code/rangladex5/vendor/laracasts/integrated/src/Extensions/IntegrationTrait.php:74
/home/vagrant/code/rangladex5/tests/functional/battertest.php:38

Latest update with ->seeJsonContains not completely right

Using this test

/** @test */
 public function it_makes_api_requests()
 {
     $this->get("fractal/{$this->batterID}")
          ->seeJson()
          ->seeStatusCode(200)
          ->dump()
          ->seeJsonContains(['name' => 'Trout, Mike', 'HR' => '37']);
 }

I receive these results (using dump() routine)

...string(142) "{"id":1318,"team":"LAA","name":"Trout, Mike","AB":602,"H":173,"2B":39,"3B":0,"HR":36,"RBI":111,"BB":83,"AVG":".287","OBP":".368","SLG":".561"}"

The 'seeJsonContains' routine is testing HR => 37 but data is actually 36 and the test passes

Confused about using TestCase in release 0.11.0

Hi, first of all congrats on this package it is very nice.

I am opening this issue because of the last release 0.11.0. I am confused on how to use it.

In the code you have:

use TestCase;
abstract class Laravel extends TestCase implements Emulator

But then in release notes you say:

If using the Laravel extension, your test classes should extend the default "tests/TestCase.php" class that is included with Laravel. Have that file extend Laracasts\Integrated\Extension\Laravel instead.

Now the issue. If my TestCase class extends Laracasts\Integrated\Extension\Laravel and then that class again extends TestCase what is going on here?

I keep getting error:

PHP Fatal error:  Class 'TestCase' not found in F:\Repositories\hotelmurter\vendor\laracasts\integrated\src\Extensions\Laravel.php on line 11

Maybe change your Laravel class to use Illuminate\Foundation\Testing\TestCase and not TestCase ?

Undefined $response property when testing Laravel API

I am trying to test a JSON API written in Laravel 4.2. I have the following test case below:

public function testWaterfallAPIDoesNotReturnWaterfallForUnkownBundleId()
 {
    $this->app->bind('\Example\Common\Model\v2\AdWaterfallRepositoryInterface', function () {
      $databaseConnectionMock = Mockery::mock();
      $databaseManagerMock    = Mockery::mock('Illuminate\Database\DatabaseManager');
      $databaseManagerMock->shouldReceive('connection')->once()->andReturn($databaseConnectionMock);

       $cacheMock = Mockery::mock('Illuminate\Cache\Repository');
       $cacheMock->shouldReceive('remember')->once()->andReturn(null);

       return new \Example\Common\Model\v2\DbAdWaterfallRepository(
            $databaseManagerMock,
            $cacheMock
        );
    });

    $this->get('v2/waterfalls/com.perk.noteven.json')->seeJson();
 }

And when I run the tests I get the following in the terminal:

1) GenericAPITest::testWaterfallAPIDoesNotReturnWaterfallForUnkownBundleId
ErrorException: Undefined property: GenericAPITest::$response

/home/vagrant/perk-tv-api/vendor/laracasts/integrated/src/Extensions/Traits/LaravelTestCase.php:113
/home/vagrant/perk-tv-api/vendor/laracasts/integrated/src/Extensions/Traits/ApiRequests.php:103
/home/vagrant/perk-tv-api/app/tests/GenericAPITest.php:31

Not sure if this is a bug, or something I am doing incorrectly.

Parenthesis Cause see() to return false

I was testing this and was surprised to find this bug, but I don't know if it belongs here or upstream or not.

public function test_delete_customer()
{
    $this->test_add_customer();
    $customer = User::where('username', '=', $this->newuser['username'])->firstOrFail();
    $this->visit('/admin/customers/' . $customer->id  )
        ->see('Customer Detail')
        ->click('Delete')
        ->onPage('/admin/customers')
        ->see('Customer ' . $customer->first_name . ' ' . $customer->last_name . ' (' .     $customer->id . ') has been deleted.');

    }

Was returning failed, even though the output indicated it was there and correct.

Changing the see() call to:

->see('Customer ' . $customer->first_name . ' ' . $customer->last_name . ' \(' . $customer->id . '\) has been deleted.');

Corrected the issue.

I think this might be an issue with accepted syntax of the PCRE and what see() is passing.

Creating additional functions

As of now, am I correct in assuming that the only way to add your own functions to the integration tests (such as dontSeeInDatabase()) is to have another base class (e.g. IntegrationTestCase) extending the Integrated Laravel class, and define the methods on there? It then becomes

TestCase > Integrated\Laravel > IntegrationTestCase

I can't place any helpers on TestCase because it's the superclass.

Undefined property: ExampleTest::$response

Laravel 4.2 (fresh install)

TestCase.php

<?php

use Laracasts\Integrated\Extensions\Laravel as IntegrationTest;

class TestCase extends IntegrationTest {

    /**
     * Creates the application.
     *
     * @return \Symfony\Component\HttpKernel\HttpKernelInterface
     */
    public function createApplication()
    {
        $unitTesting = true;

        $testEnvironment = 'testing';

        return require __DIR__.'/../../bootstrap/start.php';
    }

}

ExampleTest.php

class ExampleTest extends TestCase {

    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->visit('/');
    }
}

Run phpunit

ERROR:

There was 1 error:

1) ExampleTest::testBasicExample
ErrorException: Undefined property: ExampleTest::$response

/home/user/l4/vendor/laracasts/integrated/src/Extensions/Laravel.php:82
/home/user/l4/vendor/laracasts/integrated/src/Extensions/Laravel.php:63
/home/user/l4/vendor/laracasts/integrated/src/Extensions/IntegrationTrait.php:74
/home/user/l4/app/tests/ExampleTest.php:12

Using TerminableMiddleware 'terminate' functions is not called

Working with Laravel.

It's kind of weird but if I use the TerminableMiddleware Implementation the terminate function is not called. I thought I was doing something wrong and it could lead to wasted time trying to figure the problem in other context.

class CustomMiddleware implements TerminableMiddleware {

    public function handle($request, Closure $next)
    {
        $response = $next($request);

        return $response;
    }

    public function terminate($request, $response)
    {
        Query::createFromRequestResponse($request, $response);
    }

}

Of course, I can recreate the same behaviour using the handle function.

class CustomMiddleware {

    public function handle($request, Closure $next)
    {
        $response = $next($request);

        Query::createFromRequestResponse($request, $response);

        return $response;
    }

}

Selecting options based on their labels

Right now the functionality is:

select($selectName, $optionValue)

A lot of the forms I deal with have database uuids as the value of the <option>. Since I have no idea what those uuid values are after seeding, I need to be able select based on the text inside of the <option> tags. Is there any way to do this currently?

Problems with input arrays in form

Hello Jeffrey,

I've run into trouble on a current test, as I'm trying to test a form that has input arrays. The problem is the fact that the input data is formatted differently when submitting the form via the test, than when submitting the form via a browser.

Example:
Output from browser(when i dump the request):

array:3 [
  "facilities" => array:5 [โ–ผ
    "FacilityOne" => "1"
    "FacilityTwo" => "2"
  ]
]

Output when submitting the form from the test:

`array:4 [
  "facilities[FacilityOne]" => "1"
  "facilities[FacilityTwo]" => "2"
]

Due to this, I can no longer access the input in my controller by

$request->get('facilities');

redirect not working properly on selenium

Im trying to test if going to a protected page redirects to login. this test works ok on the laravel test.

$this->visit('/')->seePageIs('/login');

Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'http://portal.app/login'
+'http://portal.app'

If I add a wait before the seePageIs, I can see im actually on /login, but it's still seeing /. .

Installation failed

Laravel 4.2

composer require laracasts/integrated --dev

Result:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: don't install laracasts/integrated 0.10.1
    - Installation request for laracasts/integrated 0.10.* -> satisfiable by laracasts/integrated[0.10.0, 0.10.1].
    - Conclusion: remove symfony/dom-crawler v2.5.10
    - laracasts/integrated 0.10.0 requires symfony/dom-crawler ~2.6 -> satisfiable by symfony/dom-crawler[v2.6.0, v2.6.1, v2.6.2, v2.6.3, v2.6.4, v2.6.5].
    - Can only install one of: symfony/dom-crawler[v2.6.0, v2.5.10].
    - Can only install one of: symfony/dom-crawler[v2.6.1, v2.5.10].
    - Can only install one of: symfony/dom-crawler[v2.6.2, v2.5.10].
    - Can only install one of: symfony/dom-crawler[v2.6.3, v2.5.10].
    - Can only install one of: symfony/dom-crawler[v2.6.4, v2.5.10].
    - Can only install one of: symfony/dom-crawler[v2.6.5, v2.5.10].
    - Installation request for symfony/dom-crawler == 2.5.10.0 -> satisfiable by symfony/dom-crawler[v2.5.10].

Using Selenium with the PhantomJS configuration failing

With a new Laravel installation I changed the Welcome route to just return "foo". I have PhantomJS version 1.9.8 installed globally through NPM and verified that it is working and available in my $PATH. I downloaded the latest Selenium server 2.45.0 and placed the jar file into the project root. I can start up Selenium fine with java -jar selenium-server-standalone-2.45.0.jar. When I run my test however something strange is happening where Selenium doesn't seem to visit a web page. It just says "could not find 'foo' on the page, 'about:blank'." I can run the test using just the Laravel extension and PHPUnit detects 'foo' no problem. Foo also pulls up in the browser as expected. Not sure what's going on.

SomeTest.php :

<?php

use Laracasts\Integrated\Extensions\Selenium;
use Laracasts\Integrated\Services\Laravel\Application as Laravel;

class SomeTest extends Selenium
{

    use Laravel;

    /** @test */
    public function it_shows_the_home_page()
    {
        $this->visit('/')
             ->see('foo');
    }

}

integrated.json :

{
    "selenium": {
        "browser": "phantomjs"
    }
}

WelcomeController.php :

/**
* Show the application welcome screen to the user.
*
* @return Response
*/
public function index()
{
    return 'foo';
}

Result:

There was 1 failure:

1) SomeTest::it_shows_the_home_page
Could not find 'foo' on the page, 'about:blank'.
Failed asserting that '<html><head></head><body></body></html>' matches PCRE pattern "/foo/i".

/Users/Stephen/Dev/homestead/example.com/vendor/laracasts/integrated/src/Extensions/IntegrationTrait.php:121
/Users/Stephen/Dev/homestead/example.com/vendor/laracasts/integrated/src/Extensions/IntegrationTrait.php:142
/Users/Stephen/Dev/homestead/example.com/tests/acceptance/SomeTest.php:15
/Users/Stephen/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:153
/Users/Stephen/.composer/vendor/phpunit/phpunit/src/TextUI/Command.php:105

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

Any plans to support Lumen

Any (short term) plans to support Lumen with this package? I have already rolled my own using Guzzle to perform API testing, but am curious what you plan?

Maybe another extension for Lumen (ala existing extension for Laravel). Seems it would just take some minor tweaks?

see() should escape the parameter

I'm looking for a string that gets escaped in the view but see() looks for it 'raw'

    public function it_sends_a_message_through_the_contact_page()
    {
        $this->visit('contact')
            ->see('contact')
            ->fill('This is the subject','subject')
            ->fill('And this is the message', 'message')
            ->press('Send')
            ->see('Your message has been sent. You\'ll be recontacted ASAP.') // fails
            ->see('Your message has been sent. You&#039;ll be recontacted ASAP.'); // works
    }

fails with:

2) StaticPagesTest::it_sends_a_message_through_the_contact_page
Could not find 'Your message has been sent. You'll be recontacted ASAP.' on the page, 'http://localhost/contact'.
Failed asserting that '<!DOCTYPE html>
....
<div class="alert alert-success">Your message has been sent. You&#039;ll be recontacted ASAP.</div>
....
' matches PCRE pattern "/Your message has been sent\. You'll be recontacted ASAP\./i".

submitForm(): _token is saved with all other fields

Hi,

I have a problem with the following test:

$newCategory = [
    'name'      => 'TEST',
    'group_id'  => 1,
    'parent_id' => null
];

$this->visit('/categories/create')
    ->submitForm('Save', $newCategory)
    ->verifyInDatabase('categories', ['name' => 'TEST']);

I get the following error:

SQLSTATE[HY000]: General error: 1 table categories has no column named _token

Here is the code of my store method:

public function store(CategoryRequest $request)
{
    $category = new Category;
    $category->fill($request->all());
    $category->save();
}

I'm bypassing the Csrf check directly in the middleware when env is testing, so it is supposed to not use that field, but it is submitted and save() is trying to store it in the DB.

How can I avoid that?

Pv

Selenium not hitting page

Giving Selenium a run and have the following test

visit("/");
    }

}

When I run the test, it launches Firefox and then just sits there a while until it finally fails with

1) BatterTest::it_should_launch_browser
WebDriver\Exception\UnknownError: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output:

Call to a member function on null

This is my test, which worked perfectly fine on version 0.14, but breaks after updating to 0.15

I'm getting:
PHP Fatal error: Call to a member function type() on null in ContactPageTest.php on line 17

This is the code it triggers on:

    /**
     * @test
     */
    public function userCanMakeContact() {
        $this->visit('/')
            ->click('Contact Ed')
            ->see('Contact Ed, Your Computer Guy')
            ->onPage('/contact')
            ->type($this->validName, '#contactName') # Line 17
            ->type($this->validEmail, '#contactEmail')
            ->type($this->validPhone, '#contactPhone')
            ->type($this->validMessage, '#contactMessage')
            ->press('Send')
            ->see(Lang::get('contact.success'))
    }

I presume this means onPage() isn't returning $this as an object.

You know, a set of tests for this package would help prevent these problems after a major refactor. ๐Ÿ˜‰ I'd create some, but I'm concerned at my novice level I wouldn't do a decent job.

No input when submit form

Hi, when I submit a form I got no input in Input::all(), this is my code:

$this->visit('login')
->type('david', 'loginUsername')
->type('password', 'loginpassword')
->press('Login')
->see('You have logged in.');

What am I doing wrong?

exception_message should be part of failure message

When I have a undefined variable in my view I get:

1) TaskManagementTest::addingATodo
A GET request to 'http://localhost' failed. Got a 500 code instead.

ErrorException on /home/username/todos/storage/framework/views/f8106f990a36ba68910cf43a05c14374 line 10

If I turn on the server and view the error in my browser, I get the useful information that is missing from the test failure message: Undefined variable: tassks (View: /home/username/todos/resources/views/tasks/index.blade.php)

I would think it would be a good idea to display the exception message in the failure output.

A possible change could be in LaravelTestCase.php in the handleInternalError method:

$error_message = $crawler->filter('.exception_message')->text(); // span tag that has message
// ...
$message .= "\n\n{$exception} on {$location}\n\n{$error_message}";

Thanks
Timko

submitForm should accept an #id as well as the button text

Not sure if this should be the id of the form, or the id of the submit button. What do you think?

Where possible we prefer to hook our tests to page ids, as these are unique and do not change on different locales.

Ideally it would work with any valid CSS selector though.

Retrieving Response

I can see the response via dump() but is there a way to get the results (into variable) so that I can do further testing (need to make sure response is json and do some more testing on result)

base url for LaravelTestCase

I noticed that LaravelTestCase does not use the $baseUrl property.
In many cases this is just fine.
But when using route groups with domain this will break.

i suggest:

    /**
     * Get the base url for all requests.
     *
     * @return string
     */
    public function baseUrl()
    {
        if (isset($this->baseUrl)) {
            return $this->baseUrl;
        }

        return "http://localhost";
    }

Type command doesn't work when using the second time on a field

I'm trying to test a form which has various onKeyUp and onKeyDown events and also has an Ajax based auto-suggestion text input.

Issue 1 - type command only enters one character when used the second time (Selenium +Firefox)

$this->type('123','number_field')->see('3 characters typed'); //works
$this->type('123','number_field')->see('3 characters typed')->type('456','number_field')->see('6 characters typed'); //fails as only "4" gets inputted, i.e. 1234 displays

Issue 2 / Feature Request

It would be great if there were commands like:
$this->reType() - re-enter a field's value instead of appending
$this->backspace(5) - delete 5 characters from the field
$this->seeInElement('text','span#para1') - check if 'text' is there in a span with an id of 'para1'

It's difficult to test my onKeyUp or Ajax based auto-complete otherwise, or is there a better way to go about it that I'm missing?

seeJsonContains fails on partial matches

class ApiTest extends TestCase {
    public function test_users_index()
    {
        $this->get('api/users')->seeJsonContains(['id' => "1"]);
    }

fails with this error:

1) ApiTest::test_users_index
Dang! Expected {"id":"1"} to exist in [{"id":"1","username":"root","email":"root@<snip>

The same happens if i look for "id" => 1 (with the value expressed as integer).
I don't know what i'm doing wrong here, maybe it's a bug?

Add Negative Versions for Verification Tests

First off, loving this package! Because of it, I'm actually writing tests for a project for the first time. Sometimes I run my tests just to see the beautiful green, even though no code changed.

In one of my tests, I'd like to verify that a string is not on the page. It would be handy to do this:

$this->visit('/')
     ->andNotSee("It's the end of the world as we know it!")

PHPUnit has an assertNot for pretty much everything. While not relevant for action oriented tests, it would be helpful if I could be so for the verification tests like see(), seeFile(), seeInDatabase(), seePageIs() and anywhere else it seems logical to have a negative counterpart.

Although in most cases, "not" doesn't seem to be the most natural sounding word choice, especially without the "and" prefix. Maybe there's a better one.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.