如何使用 rspec 断言页面上的元素



我已经成功地集成了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

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

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

  • 呈现的模板
  • 重 定向
  • 在控制器中分配的实例变量要与视图共享
  • 与响应一起发回的饼干

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

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

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

config.include Capybara::RSpecMatchers

最新更新