RSpec: do the same wait under different circumstances

I want to make sure that the item on my website only displays when I log in.

Here is how I am achieving this at the moment:

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

It somehow seems awkward. Especially when the specification fails, I don’t get the error message that I usually get on execution expect(page).to have_content 'Statistics', I just get something like β€œthe expected result, which changed from false to true but did not change”, which isn’t very informative .

I know that there are common examples, but they feel too much for this occasion.

I tried something like the following, but failed:

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

Any ideas? I do not want to write the wait 2 times, as this is very error prone.

+4
source share
2

- .

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
+1

spec context, . , have_content have_content - <div> <span>, (, class id of statistics - )? , , , , , , , :

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
0

All Articles