【问题标题】:How to assert elements on a page with rspec?如何使用 rspec 在页面上声明元素?
【发布时间】:2014-02-21 10:53:04
【问题描述】:

我已经成功集成了 rspec gem.. 我的一些 tets 也与重定向传递有关。但是当我使用 have_tag or have_text or have_selector 时,它都不起作用...我在控制器规范文件的顶部添加了 render_views ,但我仍然收到错误:

没有达到水豚的期望!!!!

我应该怎么做才能断言/验证页面上的元素在我的测试中的某些操作后被重定向到导航到?

错误:

     Failure/Error: response.body.should have_selector(:xpath, "//*[@id='header'
]/h2")
     Capybara::ExpectationNotMet:
       expected to find xpath "//*[@id='header']/h2" but there were no matches
     # ./spec/controllers/account_controller_spec.rb:11:in `block (3 levels) in
<top (required)>'

测试:

describe AccountController do
  render_views

  describe "GET 'index'" do

    it "should redirect to /users/sign_in" do
      get 'welcome'
      #response.should redirect_to("/users/sign_in")
      response.body.should have_selector(:xpath, "//*[@id='header']/h2")
    end
 ---- some more tests---

更新: 将此添加到 spec_helper.rb,仍然没有运气!

config.include Capybara::DSL

【问题讨论】:

    标签: ruby-on-rails-3 rspec controller


    【解决方案1】:

    控制器测试的目的是验证控制器的行为。如https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs中所述:

    它允许您在每个示例中模拟单个 http 请求,并且 然后指定预期结果,例如:

    • 呈现的模板
    • 重定向
    • 在控制器中分配的实例变量与视图共享
    • cookie 随响应返回

    在控制器将您重定向到的页面上测试内容根本不在此类测试的范围内。正如它默认不呈现视图一样,它也不会导航到重定向页面。

    要验证您被重定向到您的页面上的内容,您可以使用功能规范,或者,如果您不想使用 Capybara,请使用请求规范。

    【讨论】:

      【解决方案2】:

      在我将以下内容添加到spec_helper.rb 后,所有匹配器(例如 have_selector、have_tag、have_text)都开始工作了

      config.include Capybara::RSpecMatchers
      

      【讨论】:

        猜你喜欢
        • 2018-12-17
        • 2020-02-03
        • 1970-01-01
        • 2011-06-04
        • 2014-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-06
        相关资源
        最近更新 更多