Skip to main content

Behat3.x steps of interactions with Nodes for Drupal

With the help of these two functions we can publish and unpublish nodes. Very useful if we need to have certain content to do tests on them.

Node Publishing

/**
 * @BeforeSuite
 */
public static
function publishNode() { 
  $nids = array();  // Load all nodes in one go for better performance. Example (12, 15)
   
  $nodes = node_load_multiple($nids);
  foreach($nodes as $node) {
       
    $node-> status = 1;  // set status property to 1, Published
       
    node_save($node);   //save the node
  }
}

 

Unpublished Nodes

/**
 * @AfterSuite
 */
public static
function unpublishNode() { 
  $nids = array();  // Load all nodes in one go for better performance. Example (1, 5, 15)
   
  $nodes = node_load_multiple($nids); 
  foreach($nodes as $node) {    

    $node-> status = 0; // set status property to 0, Unpublish
       
    node_save($node);   // save the node(s)
  }
}

 

Retrieve the NID of the last created node

 
 /**
   * Take the last nid create. Optional bundle
   *
   * @param string $bundle
   *   Optionally restrict the search to this type of node.
   *
   * @return int
   *   Node id (Nid).
   */
  public function getLastNodeNid($bundle = NULL) {
    if (!empty($bundle)) {
      $query = db_query("SELECT nid FROM node WHERE type = :bundle ORDER BY nid DESC LIMIT 1", array(':bundle' => $bundle));
    }
    else {
      $query = db_query("SELECT nid FROM node ORDER BY nid DESC LIMIT 1");
    }

    return $query->fetchField();
  }

 

Below is information on the tools and documentation on Behat related to the steps.

 

Tags Information @BeforeSuite y @AfterSuite
http://docs.behat.org/en/v2.5/guides/3.hooks.html#hooks

Information about Drupal Extension and Mink
http://behat-drupal-extension.readthedocs.io/en/3.1/intro.html