【问题标题】:How to rescrape a page in Capybara?如何在 Capybara 中重新抓取页面?
【发布时间】:2019-02-24 22:44:58
【问题描述】:

这是我的页面规范,该页面使用按钮触发一些 Javascript 以扩展截断的 description 文本。

     it 'gets the description and inventory', js: true do
      product = Product.create!(name: "Test Product", inventory: 0, description: "This is a test description with more text than should be there.")
      customer = Customer.create(:name => Faker::Name.name)
      invoice = Invoice.create
      order = Order.create(customer: customer, invoice: invoice)

      order.products << product
      visit products_path
      expect(page).to have_content(product.name, count: 1)
      expect(page).not_to have_content product.description
      click_button "More Info"
      expect(page).to have_content product.description
      expect(page).to have_content "Sold Out"
      product.inventory = 1
      product.save
      visit products_path
      click_button "More Info"
      expect(page).to have_content "Available"
    end

当我运行我的 Rails 服务器并在浏览器中访问该页面时,“更多信息”按钮肯定可以正常工作。但是,当我运行规范时,该按钮似乎不起作用:

  1) Products products index gets the description and inventory
     Failure/Error: expect(page).to have_content product.description
       expected to find text "This is a test description with more text than should be there." in "Flatiron Widgets Store Products Test Product This is a test description ... More Info"
     # ./spec/features/product_feature_spec.rb:47:in `block (3 levels) in <top (required)>'

现在,我知道完全有可能是某些问题导致按钮实际上无法正常工作,但我想知道问题是否实际上是我们正在检查尚未删除的 page在单击按钮之前。

有谁知道这是否确实是问题所在,如果是,有没有办法“重新抓取”页面?我不打算重新加载或刷新页面,因为这会将 JS 置于其初始按钮前状态。

【问题讨论】:

    标签: javascript ruby-on-rails capybara


    【解决方案1】:

    假设这是一个功能测试,并且您需要 capybara/rspec,如 Capybara README 中所示,那么 Capybara 应该在测试中看到 js 元数据,切换到由 Capybara.javascript_driver 配置的驱动程序(默认为 :selenium -将打开 Firefox),并且不需要重新加载/刷新/重新抓取页面,因为 Capybara 从不缓存页面(每次检查文本时,它都是针对浏览器中的实时页面)。

    如果以上都是真的并且您看到了这个问题,那么您的页面上可能有错误,或者您正在使用过时的驱动程序(Poltergeist 等)来运行不支持 JS 的测试您实际在您的页面中使用。

    【讨论】:

    • 这确实是一个使用 Poltergeist 的 Flatiron 实验室。所以,我会调查的!有一次我尝试 Selenium,我认为打开 Firefox 意味着我做错了什么!
    • @JonathanTuzman 在这个时间点上 Poltergeist 基本上相当于 7 年前的 Safari 版本。今天的替代方案是 Chrome 驱动程序的直接 CDP 之一,例如 Apparition - github.com/twalpole/apparition(目前是测试版,提供具有现代浏览器支持的 Poltergeist 功能集),或者 Capybara 使用 Selenium 预注册多个驱动程序选项(:selenium, :selenium_headless, :selenium_chrome, :selenium_chrome_headless) 或者您可以为 Selenium 注册自己的设置 - github.com/teamcapybara/capybara#configuring-and-adding-drivers
    • 谢谢!是否可以无头运行硒?答案似乎是“使用 poltergeist”,这让我们回到了开始的地方!大声笑
    • @JonathanTuzman 查看预先注册的 Selenium 配置名称。如果您指定Capybara.javascript_driver = :selenium_headless,它将使用 Selenium 和无头 Firefox(类似于 :selenium_chrome_headless 但使用 Chrome)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多