在功能测试中无法在背景块外访问 Var

Var is not accessible outside background block on 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

如果我运行这个测试我得到以下错误

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

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

我认为这是因为 post_path 中的 post 变量无法从 background 访问,对吗?

如果我将代码从 background 移动到测试场景,即

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

测试通过。

我猜在这种情况下的问题是,如果我想添加另一个场景,我必须一次又一次地重复这些步骤。我怎样才能解决这个问题并保持我的代码干燥?

您正在创建局部变量,这些局部变量在创建它们的块之外无法访问。而是使用在测试实例上创建并可用的实例变量

@post = create(:post)
...
click_link(href: post_path(@post))

附带说明一下,如果您希望在开始测试支持 JS 的页面时进行稳定的测试,请不要将 eq 匹配器与 current_path 一起使用。而是使用 have_current_path 匹配器

expect(page).to have_current_path(post_path(@post)) # You can't assume id==1 either