Skip to content

Instantly share code, notes, and snippets.

@jhedstrom
Last active April 5, 2019 10:25
Show Gist options
  • Save jhedstrom/5708233 to your computer and use it in GitHub Desktop.
Save jhedstrom/5708233 to your computer and use it in GitHub Desktop.
Step-definition for complex node structure (field collection + entity reference).
<?php
/**
* @Given /^I am viewing a product with the following related products:$/
*/
public function assertRelatedProducts(TableNode $relatedProducts) {
// First, create a product.
$product = (object) array(
'title' => 'Parent Product',
'type' => 'product',
'uid' => 1,
);
$product = $this->getDriver()->createNode($product);
// Create and reference related nodes.
foreach ($relatedProducts->getHash() as $relatedProduct) {
$relatedProduct = (object) $relatedProduct;
$relatedProduct->type = 'product';
$saved = $this->getDriver()->createNode($relatedProduct);
$this->nodes[] = $saved;
// Create field collection item.
$fieldCollectionItem = entity_create('field_collection_item', array('field_name' => 'field_related_products'));
$fieldCollectionItem->setHostEntity('node', $product);
$fieldCollectionItem->field_product_reference[LANGUAGE_NONE][0]['target_id'] = $saved->nid;
$fieldCollectionItem->field_is_component[LANGUAGE_NONE][0]['value'] = $relatedProduct->component;
$fieldCollectionItem->save();
}
// Resave product node.
node_save($product);
$this->nodes[] = $product;
// Set internal page on the product.
$this->getSession()->visit($this->locatePath('/node/' . $product->nid));
}
}
Scenario: Related products and components
Given I am viewing a product with the following related products:
| title | component |
| Related product 1 | 0 |
| Related product 2 | 0 |
| Related component 1 | 1 |
| Related component 2 | 1 |
Then I should see the heading "Related Products"
And I should see the link "Related product 1"
And I should see the link "Related product 2"
And I should see the link "Related component 1"
And I should see the link "Related component 2"
@bennyc2444
Copy link

Hey jhedstrom, Thanks so much for this, I keep receiving a message of The "field_collection_item" entity type does not exist. (Drupal\Component\Plugin\Exception\PluginNotFoundException) when running this test, am I missing something?

@ChristopheCaron
Copy link

@bennyc2444 you need to install this module https://www.drupal.org/project/field_collection and I think you need to create all entity type used in this example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment