Turtleneck and Stub Chains

The Issue

Let's walk through a sample BDD scenario. In this feature, we want to test that a user's active addresses are displayed on the user#show page. The code for that section of the page might look something like this.

  <%= render @user.addresses.active %>

This line will render out the collection of addresses to the appropriate partial. Active in this case is a scope that would restrict only addresses that have a status of "active" thing.

Let's say that setting up the addresses is cumbersome and we simply don't want to add any more weight to this feature spec. It's sole purpose is to test that addresses are active display. We could write a test for confirming the active scope as a unit test.

How can we stub @user.addresses.active in a feature spec?

stub_chain matches against a chain of methods and returns whatever value you specify. In this case, your feature spec might look something like this.

  address = build(:address) #leveraging FactoryGirl
  User.any_instance.stub_chain(:addresses, :active).and_return([address])

This is a particularly simple example but you may find scenarios where building the children object detracts from the clarify of a test. In those cases, stub_chain can come to the rescue.