Search code examples
rubycucumbercapybara

Share instance variable accross steps in Cucumber Ruby with Capybara


I'm new to Cucumber and Ruby and I want to check that data is visible on the page:

Feature

Given I am a user
And I own a thing
When I visit the page
Then I can see my thing

Steps

Given ("I am a user") do 
  @user = FactoryBot.create(:user)
end

And ("I own a thing") do 
  @thing = FactoryBot.create(:thing, user: @user)
end

When ("I visit the page") do 
  visit page_path
end

Then ("I can see my thing") do 
  expect(page).to have_text(@thing.name)
end

Result

undefined method `name' for nil:NilClass
  
    expect(page).to have_text(@thing.name)
                                     ^^^^^^ (NoMethodError)

I've tried the following without success:

When ("I visit the page") do 
  visit (page_path($thing))
end

I understand that the instance variable is not availble to me on the page but I do not know how to inject it.


Solution

  • The object was created through an association and needed to be accessed through it's parent so in my case @user.thing was the solution.