水豚的多个会话

时间:2016-04-19 08:28:58

标签: ruby cucumber capybara

背景

我想在我的webapp上测试以多个用户身份登录,并且我使用黄瓜和水豚来执行此操作。我发现this link关于如何处理多个会话,但不幸的是,看起来黄瓜不能找到定义的in_session方法。我该如何访问它?

黄瓜情景

Given I go to teacher login in Steve's browser

When I enter "Steve" in the username field 
     And I enter "StevesPassword" in the password field 
     And I click login 
Then I should see "Steve Lastname" as the current user

When I go to teacher login in Lisa's browser
     And I enter "Lisa" in the username field 
     And I enter "LisasPassword" in the password field 
     And I click login 
Then I should see "Lisa Lastname" as the current user

Ruby代码

#standard_definitions/switching_sessions.rb
When /^(.*) in (.*) browser$/ do |next_step, name|
    in_session(name) do
        step next_step
    end 
end
  #features/support/sessions.rb
  module Capybara
  module Driver
    module Sessions
      def set_session(id)
        Capybara.instance_variable_set("@session_pool", {
          "#{Capybara.current_driver}#{Capybara.app.object_id}" => $sessions[id]
        })
      end

      def in_session(id, &block)
        $sessions ||= {}
        $sessions[:default] ||= Capybara.current_session
        $sessions[id]       ||= Capybara::Session.new(Capybara.current_driver, Capybara.app)
        set_session(id)

        yield

        set_session(:default)
      end
    end
  end
end

错误

当我运行时,我得到以下内容:

Scenario: multiple users                                  # features/Provebank/Provebank.feature:23
Given I go to teacher login in Steve's browser         # features/step_definitions/standard_definitions/switching_sessions.rb:5
  undefined method `in_session' for Capybara::Driver::Sessions:Module (NoMethodError)
  ./features/step_definitions/standard_definitions/switching_sessions.rb:8:in `/^(.*) in (.*) browser$/'
  features/test.feature:24:in `Given I go to teacher login in Steve's browser'

2 个答案:

答案 0 :(得分:4)

正如文章顶部所提到的,您已将此链接“现在包含在Capybara库中”。 - 除了方法名为Capybara.using_session而不是in_session,因此您不需要feature / support / session.rb。请注意,编写测试的方式以及您共享的链接中的代码,只有以“在xxxx的浏览器中”结尾的步骤才会实际发生在不同的会话中,而不是您在这些行下标记的那些会话。要使这些步骤中的每一组都出现在他们自己的会话中,您需要在每行上“在xxx的浏览器中”,或者在步骤中使用Capybara.session_name = <name>,然后将其用于将来的步骤。如果直接设置session_name,您可能希望将其重置为:如果您希望将来的方案默认为该会话,则在After块中为default。

# only next_step will be executed in the alternate session
When /^(.) in (.*) browser$/ do |next_step, name|
  Capybara.using_session(name) do
     step next_step
  end 
end

# all future steps will be executed in the alternate session
# you probably want to reset this to :default in an After block
Given /^I switch to (.*) browser$/ do |name|
  Capybara.session_name = name
end

答案 1 :(得分:2)

如果我理解你的问题,那么一种方法是将Capybara会话重命名为:

user1 = Capybara::Session.new(:selenium)
user1.visit "foo/bar"

user2 = Capybara::Session.new(:selenium)
user2.visit "bar/foo"
user1.click_on "Sign in"
user2.click_on "Log in"

同时查看rack_session_access gem。也许这就是你要找的东西?