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

时间:2014-02-21 10:53:05

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

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

Capybara未见过!!!!

在我的测试中执行某些操作后,我应该做什么来断言/验证重定向到导航到的页面上的元素?

错误:

     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

2 个答案:

答案 0 :(得分:2)

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

中所述
  

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

     
      
  • 渲染模板
  •   
  • 重定向
  •   
  • 在控制器中分配的实例变量以与视图共享
  •   
  • 通过回复发回的Cookie
  •   

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

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

答案 1 :(得分:0)

在我将以下内容添加到spec_helper.rb

之后,所有匹配器如have_selector,have_tag,have_text都开始工作了
config.include Capybara::RSpecMatchers