Rspec: 正确使用 Let with context?

Rspec: Using Let with context correctly?

所以我正在使用页面对象模型设置构建一个自动化框架(目前使用 RSpec 和 Capybara)。我有点习惯 RSpec 但不确定我做的是否正确:

RSpec.describe 'Login', type: :feature do

  after(:all) do
    Capybara.current_session.quit
  end
  context "valid login" do
    let(:login_page) {LoginPage.new(Capybara.current_session)}
    it 'should login successfully and show dashboard' do
      expect(login_page.log_in.session).to have_content('Dashboard')
    end

    it 'should logout successfully after login' do
      dashboard = login_page.log_in
      expect(dashboard.log_out.session).to have_content('Log In')
    end
  end

  context "invalid login" do
    let(:login_page) {LoginPage.new(Capybara.current_session)}
    it 'should fail to log in successfully and display alert' do
      expect(login_page.log_in('bademail@email.com', 'badpassword').session).to have_content('bad login info')
    end

    it 'should give an error when not entering an email' do
      expect(login_page.log_in('', 'badpassword').session).to have_content('Please enter email')
    end
  end

end

特别是因为我手动处理会话,我希望它在每个 context 之后退出,但它在 describe 块之后退出会话。

我也不确定我是否正确使用 let。因为我试图在每个 it 块之前捕获当前会话并创建一个新的页面对象。

(也许是一个次要的 ruby 问题,但是用 let 创建的变量是在 it 块之后销毁还是?)

谢谢

let 本身不会被调用,除非您将它与 ! 一起用作 let!。没有 ! let 就像方法定义一样,因此在 it 块中调用它之前不会使用它。 let! 将在每个类似于 before 块的 it 示例之前被调用。

这意味着如果你想稍微清除你的代码,你可以在 context 块之外的 describe 块中只使用一次 let 然后在 it 像现在一样阻塞。

至于after(:all)它只会在所有测试完成后调用一次。如果您想在每套西装后使用它,after(:each) 是您的最佳选择。您可以在此处阅读更多相关信息:https://relishapp.com/rspec/rspec-core/v/2-2/docs/hooks/before-and-after-hooks

查看您的示例,我不确定是否有必要使用此 after 块 - Capybara 应在每个 it 示例后重置会话,除非有任何其他设置。 (我在这里可能是错的 - 与 Capybara 的合作不多)。