在功能测试

时间:2017-02-28 21:49:12

标签: ruby-on-rails unit-testing testing rspec capybara

我正在进行以下功能测试

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中的post_path变量无法从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

测试通过。

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

1 个答案:

答案 0 :(得分:0)

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

@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