在我看来,从你重构尝试有点混乱。
首先,您看到0 examples, 0 failures
的原因是因为测试中没有主题调用。想想是这样的:
subject { visit articles_path }
it 'has a nice title' do
subject
expect(page).to have_content(article.title)
end
it 'has a nice comment' do
subject
expect(page).to have_content(article.comment)
end
为了您的期望工作,您需要调用该主题。事实上,你可以通过在你的it/specify
块写明确visit articles_path
it 'has a nice title' do
visit articles_path
expect(page).to have_content(article.title)
end
it 'has a nice comment' do
visit articles_path
expect(page).to have_content(article.comment)
end
测试共享相同的主题可以用subject { ... }
竭使用主题甚至避免。
其次,不要混淆context
块和specify/it
块(记住它们是别名)。 A context
是一种通过为测试分离不同结果来让测试更易于理解的方法。
subject { visit articles_path }
context 'user is logged in' do
it 'displays article's title' do
login_as :user
subject
expect(page).to have_content(article.title)
end
it 'displays article's title' do
login_as :user
subject
expect(page).to have_content(article.comment)
end
end
context 'user not logged in' do
it 'displays article's comments' do
subject
expect(page).to have_content('Log in')
end
end
你可以有不同的期望,它/在相同的上下文中指定块。 使用不同的上下文来指定相同功能的不同行为。
最后最后一步。在before
块中分组共享功能。在我们的例子:
subject { visit articles_path }
before do
subject
end
context 'user is logged in' do
before do
login_as :user
end
it 'displays article's title' do
expect(page).to have_content(article.title)
end
it 'displays article's title' do
expect(page).to have_content(article.comment)
end
end
context 'user not logged in' do
it 'displays article's comments' do
expect(page).to have_content('Log in')
end
end
正如你可以看到,这两个上下文中运行的问题,但只有第一个内容登录的用户,而第二上下文不测试文章页面。 我希望这是有用的。
继续测试,很快就会成为习惯问题,您将很容易编写测试。
事情是我有更多的上下文共享相同的'let!/ visit'共享上下文。我认为我可以在'context'中做'实际测试','expect after {expect}';结束' – firedev 2014-10-18 11:56:14
请参阅我编辑的解决方案,我不知道你为什么要将验证码放在after块之后。 – Alireza 2014-10-18 12:48:32
在这种情况下'{login_as:user}'之前的'将在{before {visit articles_path}之前执行,并且为了使您的示例工作,我必须在{login_as:user;访问'context'块中的articles_path}。 – firedev 2014-10-18 13:47:59