mardi 28 février 2017

Var is not accessible outside background block on feature test

I'm having the following feature test

RSpec.feature 'Show post', :type => :feature do

  background do
    post = create(:post)
    user = create(:user)
    sign_in_with user # do login
  end

  scenario 'can view a single post' do
    visit root_path
    click_link(href: post_path(post))
    expect(page.current_path).to eq(post_path(1))
  end
end

If I run this test I get the following error

Show post can show idividual post
     Failure/Error: click_link(href: post_path(post))

     NameError:
       undefined local variable or method `post' for #<RSpec::

Which I think is caused because the post variable inside post_path is not accessible from the background, am I right ??

If I move the code from the background to the test scenario, ie

scenario 'can show idividual post' do
    post = create(:post)
    user = create(:user)

    sign_in_with user

    visit root_path

    click_link(href: post_path(post))
    expect(page.current_path).to eq(post_path(1))
  end

the test passes.

The problem I guess in this cases is if I want to add another scenario I have to repeat these steps again and again. How can I solve this and keep my code DRY?

Aucun commentaire:

Enregistrer un commentaire