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
测试通过。
我想在这种情况下的问题是,如果我想添加另一个场景,我必须一次又一次地重复这些步骤。我该如何解决这个问题并让我的代码保持干爽?
天啊!太傻了!我没有想到最明显的事情!无论如何,非常感谢! :-) – Lykos
@Lykos欢迎您,请确保您阅读我关于'have_current_path'的更新,如果您习惯了从一开始就使用它,您将在稍后感谢我。 –
我用它,因为你说,但这会引发错误'失败/错误:expect(page).to have_current_path(post_path(@path)) ActionController :: UrlGenerationError: 没有路由匹配{:action =>“显示“,:控制器=>”帖子“,:ID =>无}缺少必需的键:[:ID]''我猜抱怨ID – Lykos