Testing HTML 5 form validations when using simple_form Rails

落爺英雄遲暮 提交于 2019-12-07 02:23:00

问题


I'm using devise and simple_form for my todo list app . Now , I have the following code for my users/edit.html.erb

<%= content_for :title,'Edit profile' %>
<h2>Edit profile</h2>
<%= simple_form_for current_user, class: 'form-horizontal' do |f| %>
  <%= f.input :nick_name %>
  <%= f.submit 'Update profile' %>
<% end %>

My user.rb looks like this :

class User < ActiveRecord::Base  
 devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
 attr_accessible :email,:nick_name, :password, :password_confirmation, :remember_me
 validates :nick_name, presence: true    # the other fields already validated by devise
 has_many :lists , dependent: :destroy
end

Now, when I click on submit button with an empty nick_name field ,I get a popup kind of alert . It's not like a normal browser alert ,I think its a HTML5 feature . I get this message Please fill out this field as a popup below the empty field . I have disabled javascript, but it still shows the same message . This is my nick_name input field :

<input class="string required" id="user_nick_name" name="user[nick_name]" required="required" size="50" type="text">

Now, when I remove the presence validation for nick_name in my model , this popup doesn't appear .When validation line is commented out ,

<input class="string optional" id="user_nick_name" name="user[nick_name]" size="50" type="text">

Is simple_form doing some behind the scenes magic ?

Since this popup doesnt show any trace of html code , How to test for this validation in capybara/rspec ?


回答1:


Actually you can test it by finding html attribute required="required" with the following code example:

expect(page).to have_xpath("//input[@required='required']")



回答2:


Since you are using the required="required" attribute, this triggers an HTML5 validation.

To test this: message = find("#user_nick_name").native.attribute("validationMessage") expect(message).to eq "Please fill out this field"



来源:https://stackoverflow.com/questions/17384428/testing-html-5-form-validations-when-using-simple-form-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!