Testing login with Capybara / Rspec

capybararspec2ruby-on-rails-3

I am having some difficulty in testing my login procedure. Currently, I have the following request spec:

     describe "GET /admins" do
        before(:each) do
          @admin = Factory.create(:user, :winery => nil, :email => 'admin@example.com', :admin => true)
          @attr = { :email => @admin.email, :password => @admin.password }
        end


    it "should log admin users in" do
      visit admin_path
      post_via_redirect admin_path, :session => @attr
      save_and_open_page
      page.should have_content('Admin Dashboard')
    end
  end

This is failing, and the save_and_open_page, just shows my login page (I can log in normally to my development site, so the actual code works). I have also tried writing the spec using Capybara to fill in the form and click the log in button, with the same failure. I have been able to write a passing spec in Cucumber, but only with selenium.

using:
Capybara (0.4.1.2)
Rspec (2.5.0)
rspec-rails (2.5.0)
rails (3.0.5)

thanks

Best Answer

You should be using pure Capybara helpers here, post_via_redirect is a Rails method. You will first want to fill out the form then press some sort of submit button, like this:

visit admin_path
fill_in "Login", :with => "username"
fill_in "Password", :with => "password"
click_button "Submit"

Your final assert, I would be more precise and say in which selector that content should be shown, like this:

within_scope("h1") do
  page.should have_content('Admin Dashboard')
end

Now you're testing properly!

Related Topic