Posting invalid form data in SilverStripe unit tests

by frank on November 8, 2011

in SilverStripe

By default posting form data from a SilverStripe unit test seems to restrict your POST data to only valid values. Meaning, if you want to post a value for a select field on the form, the value must be in the options for that select field in order for it to be POST’d.

Usually when submitting form data from a unit test its easiest to use the FunctionalTest->submitForm() function with something like:

$this->get(Director::makeRelative($page->Link())); 
$this->submitForm('Form_SomeForm', null, array(
  'Quantity' => 1
));

But, for sending any POST data you like to a form the easiest way I have found is to grab the existing form data in an array format and then use FunctionalTest->post() to send that data, that way you can set any values you like in the data array, e.g:

/**
 * Helper to get data from a form.
 * 
 * @param String $formID
 * @return Array
 */
function getFormData($formID) {
  $page = $this->mainSession->lastPage();
  $data = array();
 
  if ($page) {
    $form = $page->getFormById($formID);
    if (!$form) user_error("Function getFormData() failed to find the form {$formID}", E_USER_ERROR);
 
    foreach ($form->_widgets as $widget) {
 
      $fieldName = $widget->getName();
      $fieldValue = $widget->getValue();
 
      $data[$fieldName] = $fieldValue;
    }
  }
  else user_error("Function getFormData() called when there is no form loaded.  Visit the page with the form first", E_USER_ERROR);
 
  return $data;
}
 
function testSomething() {
 
  $data = $this->getFormData('Form_SomeForm');
  $data['SomeFormField'] = 3;
 
  $this->post(
    Director::absoluteURL($page->Link()),
    $data
  );
}

Its not the best method, I’m pretty sure the _widgets variable is intended to be private lol, but it works.

Was this article useful?

rss feed icon

Email this article to yourself or...

rss feed icon

Subscribe to the RSS feed for more useful articles and tips.

Share this article with others

  • del.icio.us
  • Twitter
  • Reddit
  • StumbleUpon
  • Facebook
  • Digg