Aks..
Aks..

Reputation: 1383

How to assert elements on a page with rspec?

I have successfully integrated rspec gem.. some of my tets related to redirect pass too. But when i use have_tag or have_text or have_selector , none of it works... I have added render_views on top of my controller spec file, still I get the error:

Capybara expection not met!!!!

What am I supposed to do to assert/verify an element on a page that is redirected to navigated to after some action in my test???

Error:

     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)>'

Test:

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---

Update: added this to spec_helper.rb, still no luck!

config.include Capybara::DSL

Upvotes: 0

Views: 1168

Answers (2)

Aks..
Aks..

Reputation: 1383

All the matchers like have_selector, have_tag, have_text started working after I added the following to spec_helper.rb

config.include Capybara::RSpecMatchers

Upvotes: 1

Peter Alfvin
Peter Alfvin

Reputation: 29409

The purpose of controller tests is to validate the behavior of the controller. As described in https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs:

It allows you to simulate a single http request in each example, and then specify expected outcomes such as:

  • rendered templates
  • redirects
  • instance variables assigned in the controller to be shared with the view
  • cookies sent back with the response

Testing content on a page that the controller has redirected you to is simply not in the scope of such tests. Just as it doesn't render views by default, it doesn't navigate to redirected pages.

To verify content on a page that you've been redirected to you, you can use a feature spec or, if you don't want to use Capybara, a request spec.

Upvotes: 1

Related Questions