How to get RSpec test working with Factory Girl?

I am new to RSpec and trying to test the presence of dynamic content in a drop-down navigation menu. The values show up on the site but my test is failing. Am I missing something with the setup of Factory Girl? Is there a way to see the values that should be created in the test db to see if they are correct?

Please let me know if I can provide other details.

Here is my factory (spec/factories/restaurants.rb)

FactoryGirl.define do
  factory :restaurant do
    name "Corner Pub"
  end
end

from the spec.rb:

require "rails_helper.rb"

feature "user can navigate to a restaurant page" do
  let(:restaurant) { FactoryGirl.create(:restaurant) }
  scenario "views a restaurant page" do
    visit root_path
    within('#restaurants'){
      within('.submenu'){
        click_on 'Corner Pub'
      }
    }
end

the error message I get:

 Failure/Error: click_on 'Corner Pub'
 Capybara::ElementNotFound:
   Unable to find link or button "Corner Pub"

The let block is lazy-evaluated – it will only run when restaurant is first referenced. But your spec doesn’t reference it anywhere, so it’s never evaluated.

You have a few options:

  • Use let! instead of let to force it be evaluated immediately

  • Change the let block into a before block

  • Move the FactoryGirl call to within the scenario body.

1 Like