Search code examples
htmlperlcss-selectorsmojolicious

Mojolicious Tests: How to get the input value using css-selectors


I am writing a test for a Mojolicious Application, which sends some HTML form data and then checks, if they show up in the subsequent get request.

$t->post_ok('/intern/offer/edit'  => form  => {
      'angebotsdatum'    => '2014-02-22',
      'gastname'         => 'Hansi Hinterseer',
      'einmalkosten'     => '128.00',
      'tage'             => '9',
      'ankunft'          => '2014-01-01',
      'gesamtpreis'      => '764.00',
      'abfahrt'          => '2014-01-10',
      'tagespreis'       => '70.71',
      'apartments_id'    => 'HAG28',
      'id'               => '1',
      'aufenthaltspreis' => '636.39'
    }
)
->status_is(200)
->content_like( qr/Angbot bearbeiten/ )
;

$t->get_ok('/intern/offer/edit/1')
    ->status_is(200)
    ->text_like('html body h2' => qr/Intern - Angebote/ )
    ->text_like('html body h3' => qr/Angbot bearbeiten/ )
    ->text_is('html body form div#adatum label' => 'Angebotsdatum:' )
    ->text_is('html body form div#adatum input#angebotsdatum value'  => '2014-02-22' )
; 

Unfortunately the last test for the value of the input element fails, since the returned value is always empty. The test for the form-label (here 'Angebotsdatum:') succeeds.

How can I select and get back the input-elements value from a HTML-form?

The HTML-code of the form is:

<div id="adatum">
    <label>Angebotsdatum:</label>
    <input type="text" name="angebotsdatum" value="2014-02-22" id="angebotsdatum">
</div>

And this is the test-output:

#   Failed test 'exact match for selector "html body form div\#adatum input[name=angebotsdatum] value"'
#   at t/1210-workflow_booking.t line 80.
#          got: ''
#     expected: '2014-02-22'

So we can see clearly, that the CSS-selector returns the empty value.


Solution

  • From the Test::Mojo

    The text_is - Checks text content of the CSS selectors first matching HTML/XML element for exact match with at in Mojo::DOM.

    The at method

    Find first element in DOM structure matching the CSS selector and return it as a Mojo::DOM object or return undef if none could be found. All selectors from "SELECTORS" in Mojo::DOM::CSS are supported.

    And the

    html body form div#adatum input#angebotsdatum value
                                                 ^^^^^^ - this isn't valid
    

    IMHO, isn't valid CSS selector.

    You can try the next (shortened) selector:

    div#adatum > input[value="2014-02-22"]
    

    so find the element <input> what has an attribute equal to 2014-02-22.

    E[foo="bar"] An E element whose foo attribute value is exactly equal to bar.

    More info Mojo::DOM::CSS#SELECTORS

    So, it is enough test the existence of the element exactly with the wanted value:

    ->element_exists('input[value="2014-02-22"]', '...');
    

    Ps: I'm not an very experienced Mojo developer, so ...