2017-02-28 66 views
0

我有以下特性测试无功不在功能测试外部访问后台块

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 

测试通过。

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

回答

0

你正在创建局部变量不属于他们是在创建块外部访问,而是使用其创建和提供的测试实例

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

在一个侧面说明实例变量,不要使用eq匹配器current_path如果您想在开始测试JS功能的页面时进行稳定测试。而是使用have_current_path匹配器

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

天啊!太傻了!我没有想到最明显的事情!无论如何,非常感谢! :-) – Lykos

+1

@Lykos欢迎您,请确保您阅读我关于'have_current_path'的更新,如果您习惯了从一开始就使用它,您将在稍后感谢我。 –

+0

我用它,因为你说,但这会引发错误'失败/错误:expect(page).to have_current_path(post_path(@path)) ActionController :: UrlGenerationError: 没有路由匹配{:action =>“显示“,:控制器=>”帖子“,:ID =>无}缺少必需的键:[:ID]''我猜抱怨ID – Lykos