【问题标题】:Cookies within a cucumber test using capybara使用水豚进行黄瓜测试中的饼干
【发布时间】:2013-06-22 05:32:40
【问题描述】:

作为我对网站的集成测试的一部分,我使用 cucumber 和 capybara。似乎水豚无法模仿使用 cookie。

例如我在用户登录时设置cookie:

    def sign_in(user)
      cookies.permanent.signed[:remember_token] = [user.id, user.salt]
      current_user = user
    end

但是,当我稍后使用 cookies.inspect 获取 cookie 的值时,它会返回 {} 这是水豚的已知限制吗?如果是这种情况,如何通过多个请求测试登录用户?

我应该添加我的测试:

Scenario: User is signed in when they press Sign In
 Given I have an existing account with email "bob@jones.com" and password "123456"
 And I am on the signin page
 When I fill in "Email" with "bob@jones.com"
 And I fill in "Password" with "123456"
 And I press "Sign In"
 Then I should see "Welcome Bob Jones"

【问题讨论】:

    标签: ruby-on-rails cucumber capybara


    【解决方案1】:

    这是适合我的步骤。它将cookie“admin_cta_choice”设置为等于从输入值派生的模型ID。

    Given /I have selected CTA "([^"]+)"/ do |cta_name|
      cta = Cta.find_by_name(cta_name)
      raise "no cta with name '#{cta_name}'" if cta.nil?
    
      k = "admin_cta_choice"
      v = cta.id
    
      case Capybara.current_session.driver
      when Capybara::Poltergeist::Driver
        page.driver.set_cookie(k,v)
      when Capybara::RackTest::Driver
        headers = {}
        Rack::Utils.set_cookie_header!(headers,k,v)
        cookie_string = headers['Set-Cookie']
        Capybara.current_session.driver.browser.set_cookie(cookie_string)
      when Capybara::Selenium::Driver
        page.driver.browser.manage.add_cookie(:name=>k, :value=>v)
      else
        raise "no cookie-setter implemented for driver #{Capybara.current_session.driver.class.name}"
      end
    end
    

    【讨论】:

      【解决方案2】:

      这是在运行功能时显示 cookie 内容的好方法

      https://gist.github.com/484787

      【讨论】:

      • 非常好。我不知道你是否需要这个,但如果你只是使用 rack-test 以下应该让你也设置任何标题。 Capybara.current_session.driver.options ||= {} Capybara.current_session.driver.options[:headers] ||= {} Capybara.current_session.driver.options[:headers][...] = ...跨度>
      • 这个人已经对这段代码进行了宝石化。 github.com/nruth/show_me_the_cookies
      【解决方案3】:

      为什么不直接使用 selenium 运行测试?只需在要使用真实浏览器运行的场景之前添加@selenium 标签。 :)

      【讨论】:

      • 我不是 OP,但我知道我希望测试尽可能快。所以任何时候我都可以避免打开浏览器就更好了。
      【解决方案4】:

      截至本文发布之日,该要点对我不起作用,但确实如此,而且更简单:

      http://collectiveidea.com/blog/archives/2012/01/05/capybara-cucumber-and-how-the-cookie-crumbles/

      【讨论】:

      • 这个页面真的把我搞砸了。它有效,但它破坏了我页面的 javascript 设置 cookie 的能力。我不得不删除他们的代码并找到另一种方法。
      【解决方案5】:

      Capybara 没有用于读取和设置 cookie 的 API。

      但是,您可以非常轻松地模拟 Capyabara 的登录 - 只需访问登录链接。这将使您登录,包括为您设置所有 cookie。

      要查看实际情况,只需查看我的example Rails app

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多