0
votes

I'm trying to use capybara to simulate a login to test my login form, however it cannot find the email or password fields.

I have checked the page source to confirm that I am using the right ID, and I have also tried using the field names.

Here is my current test:

it "returns http success" do
      user = FactoryGirl.create(:user)
      visit sessions_new_path
      fill_in 'email', :with => user.email
      fill_in 'password', :with => user.password
      click_button('submit')
      expect(response).to have_http_status(:success)
    end

My form:

= form_for(:session, url: login_path, :html => {class: 'login_form'}) do |f|
    .field
      = f.email_field :email, 'data-msg-required' => t('email_required'), :placeholder => t('.form_email'), id: 'email'
    .field
      = f.password_field :password, 'data-msg-required' => t('password_required'), :placeholder => t('.form_pwd'), id: 'password'
    = f.submit t('.form_sbmt'), class: 'btn-submit'

When viewing the page source the IDs are listed as email and password (for the respective fields), and the names follow the format "session[email]". I've tried using "sessions[email]" (and equiv for password) for fill_in but had no luck.

Error I'm getting:

Failure/Error: fill_in 'email', :with => user.email

     Capybara::ElementNotFound:
       Unable to find field "email"

Any help would be appreciated.

2

2 Answers

1
votes

Capybara isn't used in controller tests. Capybara is used for end-to-end testing of your app (feature tests) and isn't limited to just testing the controller. The controller test for your action should be something like

it "returns http success" do
  user = FactoryGirl.create(:user)
  post :create, session: { email: user.email, password: user.password}
  expect(response).to have_http_status(:success)
end

which will be very quick and have no need to render the views.

0
votes

So I found the answer. I didn't realise Rspec does not render views when running controller tests (as it expects views to be tested separately). In order to get the controller tests to render a view you just need to add renders_view within one of your describe-do blocks (but NOT inside the it-do block).

Seems my tests are now working.

Not really a suitable answer as discussed in the comments.