RSpec:在不同的情况下执行相同的期望
我想确保我的网站上的一个元素只在登录时显示 我现在就是这样做到的:RSpec:在不同的情况下执行相同的期望,rspec,Rspec,我想确保我的网站上的一个元素只在登录时显示 我现在就是这样做到的: it 'displays statistics when logged in' do expect { login_as(create :user) refresh_page }.to change { page.has_content? 'Statistics' }.from(false).to true # I know, "to true" is redundant here, but
it 'displays statistics when logged in' do
expect {
login_as(create :user)
refresh_page
}.to change {
page.has_content? 'Statistics'
}.from(false).to true # I know, "to true" is redundant here, but I like it to be explicit
end
这感觉有点笨拙。特别是,当规范失败时,我没有得到通常在执行expect(页面)时得到的好的错误消息。要获得内容“统计信息”
,我只会得到类似“预期结果已从false更改为true,但未更改”这样的信息,但信息量不大
我知道有一些共同的例子,但对于这个案例,他们感觉有点太多了
我尝试了以下方法,但也没有成功:
it 'displays statistics when logged in' do
expect(expect_to_have_content_statistics).to raise_error
login_as(create :user)
refresh_page
expect_to_have_content_statistics
end
def expect_to_have_content_statistics
expect(page).to have_content 'Statistics'
end
有什么想法吗?我不想写两次期望值,因为这很容易出错。您正在测试两个不同的案例-建议将它们分开
describe 'statistics' do
def have_statistics
have_content('Statistics')
end
before { visit_statistics_page }
it { expect(page).to_not have_statistics }
it 'displays statistics when logged in' do
login_as(create :user)
expect(page).to have_statistics
end
end
我会将规范分成两个
上下文块,因为您正在测试两个不同的用例。此外,您是否有某种
或
标签包装统计信息内容(可能有类或id
的统计信息或其他内容),而不是在页面上检查硬编码的基于文本的内容?如果不是,您可能需要考虑其中一个,如果是这样,那么考虑更改您的规格,以检查该选择器是否存在取决于用户是否登录:
RSpec.feature 'Statistics' do
context 'when user is not logged in' do
before do
visit statistics_path # or whatever path this is
end
it 'does not display the statistics' do
expect(page).to_not have_selector('.statistics')
end
end
context 'when user is logged in' do
before do
login_as(create :user)
visit statistics_path # or whatever path this is
end
it 'displays the statistics' do
expect(page).to have_selector('.statistics')
end
end
end
为什么不写expect(第页)。第一个期望没有内容('Statistics')
.not_to…
)将一直通过,即使我将标题“Statistics”更改为其他名称,并且忘记更新“阴性测试”。所以我真的希望只写一次期望值,然后执行两次:一次期望值通过,一次期望值失败。@Joshuamheim:Dreaming thehave_content('Statistics
)` matcher应该涵盖这种情况。你会怎么做?谢谢,这看起来很有希望。我会检查的,这很有效。尽管如此,我还是觉得这很容易出错,因为规范是松散耦合的,它们很可能在重构过程中被撕开,东西被删除,突然之间你有了取之不尽的规范和误报。无论如何,我认为这是正确的答案。