Capybara::ElementNotFound: - ruby-on-rails-3

I am testing my Rails app's sign up form with RSpec and Capybara. When I want to test it I face this error,
Failures:
1) user registration allows new users to register with an email address and password
Failure/Error: fill_in "Confirmation", :with => "foo"
Capybara::ElementNotFound:
no text field, text area or password field with id, name, or label 'Confirmation' found
# ./user_spec.rb:9:in `block (2 levels) in <top (required)>'
This is my form which is a sign up form,
<div id="box">
<div class="block" id="block-signup">
<h2>Sign up</h2>
<div class="content">
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :class => "form login"}) do |f| %>
<% if #user.errors.any? %>
<div id="errorExplanation">
<h2><%= pluralize(#user.errors.count, "error") %> prohibited
this post from being saved:</h2>
<ul>
<% #user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<%end%>
<div class="group wat-cf">
<div class="left">
<label class="label"><%= f.label :email %></label>
</div>
<div class="right">
<%= f.email_field :email %>
<span class="description">Ex: test#example.com</span>
</div>
</div>
<div class="group wat-cf">
<div class="left">
<label class="label"><%= f.label :password %></label>
</div>
<div class="right">
<%= f.password_field :password %>
<span class="description">Must contains the word 'yeah'</span>
</div>
</div>
<div class="group wat-cf">
<div class="left">
<label class="label"><%= f.label :confirmation %></label>
</div>
<div class="right">
<%= f.password_field :password_confirmation %>
<span class="description">Don't miss any letters</span>
</div>
</div>
<div class="group navform wat-cf">
<button class="button" type="submit">
<%= f.submit "Sign in", :type => :image, :src => "http://pilu.github.com/web-app-theme/images/icons/tick.png" %>
</button>
</div>
<% end %>
</div>
<div id="links-sup">
<h4><%= render "links" %></h4></div>
</div>
</div>
And my test file is spec/requests/user_spec.rb
require 'spec_helper'
describe "user registration" do
it "allows new users to register with an email address and password" do
visit "/users/sign_up"
fill_in "Email", :with => "user#eample.com "
fill_in "Password", :with => "foo"
fill_in "Confirmation", :with => "foo"
click_button "Sign up"
page.should have_content("Welcome! You have signed up successfully.")
end
end
You have any idea to solve it?

Well, the error here indicates that it cannot find textbox with label "Confirmation". Here you have problem with html. There is no textbox with Confirmation label. You can test by clicking that label "Confirmation", the cursor won't be in the password_confirmation textbox.
See the difference why click on "Password" label, the cursor is in the password textbox. That's why there is no error on password field.
You could change the markup a little bit to f.label :password_confirmation.
When you see the error Capybara::ElementNotFound, it simply means it cannot find that element you reference. Therefore you need to check your markup is correct.

Related

Allow closing a modal when clicking outside

I used bootstrap-modal plugin for my project. But now I have an issue with closing my modal by clicking outside of it. I tried to pass the options like: data-backdrop="true", but it doesn't work. Any ideas of what's going wrong?
EDITED:
My modal is in a partial (using Rails)
<div id="editModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<div class="text-center">
<div class="btn-group topbar header-buttons" role="group" aria-label="...">
<%= link_to 'Add', '#addModal', { 'class' => 'btn btn-default', 'data-toggle' => 'modal', 'data-dismiss' => 'modal' } %>
<%= link_to 'Edit', '#', class: 'btn btn-default disabled' %>
<%= link_to 'Delete', '#deleteModal', { 'class' => 'btn btn-default', 'data-toggle' => 'modal', 'data-dismiss' => 'modal' } %>
</div>
</div>
</div>
<div class="modal-body">
<%= form_for (#change_office_address), remote: true, format: :json, html: { class: :contact_form } do |f| %>
<div id="error_explanation" style='display:none;' class="bg-danger text-danger alert fade in alert-danger alert-dismissable errors">
<ul>
<% if #change_office_address.errors.any? %>
<% #change_office_address.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
<% end %>
</ul>
</div>
<%= f.text_field :name, placeholder: 'Name', class: 'form-control' %>
<br>
<%= f.text_field :email, placeholder: 'e-mail', class: 'form-control' %> <br>
<%= f.label :city_id %>
<%= f.collection_select :city_id, City.order(:name), :id, :name,
{ include_blank: true }, { class: 'form-control' } %>
<br>
<%= f.label :insurer_id %>
<%= f.collection_select :insurer_id, Insurer.order(:short_name), :id, :short_name,
{ include_blank: true }, { class: 'form-control' } %>
<br>
<%= f.label :office_id %>
<%= f.collection_select :office_id, Office.order(:name), :id, :name,
{ include_blank: true }, { class: 'form-control' } %>
<br>
<%= f.text_area :edit_office_address, placeholder: 'New address', class: 'form-control', cols: '30',
rows: '5' %> <br>
<div class="text-center">
<%= f.submit, class: 'btn btn-default' %>
</div>
<% end %>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
I call a modal by: <%= link_to 'Edit', '#editModal', {'data-toggle' => 'modal'} %>
Thanks ahead!
I added this code, and now it's working:
$("#myModal").click(function(ev){
if(ev.target != this) return;
$('#myModal').modal('hide');
});
Backdrop option is true by default.
Check: http://getbootstrap.com/javascript/#modals-options
Make sure if you're call jquery.min.js and bootstrap.min.js correctly.
To test, press the Esc key and see if the modal is closed. By default, the keyboard option is also true.
If backdrop and keyboard doesn't working, there is a great chance you've called the .js wrongly.
Remember: call jquery.js BEFORE bootstrap.js.
If necessary, comment your console log here.
Finally, remember that Bootstrap does not support multiple modals.

Why can I create a model with an hstore attribute, but get a 500 error when I try to update?

Borrowing heavily from:
https://github.com/heroku/hstore_example
I can define any number of "params" (my hstore column) from the New view when creating a new model and the hstore column gets set properly and the model is saved. Perfect!!
However, when I try to edit and submit I'm getting:
expected Hash (got String) for param `id'
Where 'id' is the name I gave to the hstore key of the "param" that I created.
Also interesting...I can Create AND Update the SAME MODEL from the console no problem.
WTF?!?
Here's my model:
class Testmethod < ActiveRecord::Base
attr_accessible :name, :params
serialize :params, ActiveRecord::Coders::Hstore
def as_json(options = {})
{ :name => name, :params => params }
end
end
Here's the form:
<%= form_for(#testmethod) do |f| %>
<% if #testmethod.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#testmethod.errors.count, "error") %> prohibited this testmethod from being saved:</h2>
<ul>
<% #testmethod.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :script %>
<%= f.text_area :script, :rows => 6 %>
</div>
<h4>Parameters</h4>
<div class="well">
<div class='clearfix attributeContainer'>
<div class='row'>
<p class='span3 underline'>Name</p>
<p class='span3 underline'>Value</p>
</div>
<% #testmethod.params.try(:each) do |key, value| %>
<div class="row">
<p class='span3'>
<%= text_field_tag key, key, :class => 'text_field dynamicAttributeName' %>
</p>
<p class='span3'>
<%= text_field key, :class => 'text_field', :value => value %>
</p>
<p class='span1'>
<a herf='#' class='btn removeRow'>X</a>
</p>
</div>
<% end %>
<div class='row attributeTemplate <%= 'hide' if #testmethod.params.present? %>'>
<p class='span3'>
<input class='text_field dynamicAttributeName' id='' name='' placeholder='New Attribute name' size='30' type='text' />
</p>
<p class='span3'><input class='text_field' id='bar' name='' placeholder='value' size='30' type='text' /></p>
<p class='span1'><a herf='#' class='btn removeRow'>X</a></p>
</div>
<%= link_to 'Add Parameter', '#', :class => 'btn addAttribute btn-mini' %>
</div>
</div>
<div class="row">
<div class="span12">
<div class="actions">
<%= f.submit "Save", :class => 'btn btn-primary ' %> or <%= link_to "Cancel", request.referrer || testmethods_path %>
</div>
</div>
</div>
<% end %>
<%= content_for :js do %>
<script type='text/javascript'>
$('.attributeContainer').delegate('.dynamicAttributeName', 'keyup', function(event){
nameElem = $(this);
valueElem = nameElem.closest('.row').children('p').children('.text_field')
value = nameElem.val().toLowerCase();
valueElem.attr('id', 'testmethod_params_' + value );
valueElem.attr('name', 'testmethod[params][' + value + ']');
valueElem.attr('placeholder', 'value for ' + value );
})
$('.attributeContainer').delegate('.removeRow', 'click', function(){
console.log($(this).closest('.row'))
$(this).closest('.row').html('');
})
$('.addAttribute').on('click', function(){
contents = "<div class='row'>" + $('.attributeTemplate').html() + '</div>';
$(this).before(contents);
})
</script>
<% end %>

Rails two related models in one form not saving

My form fields are:
<%= form_tag signup_path, :class=>"no-ajax form-signin" do %>
<fieldset>
<legend>Company</legend>
<div class="field">
<label>Company Name</label>
<%= text_field :company, :name, :class => "input-block-level" %>
</div>
<%= hidden_field :company, :accounttype_id, :value => 2 %>
</fieldset>
<fieldset>
<legend>User</legend>
<div class="field">
<label>First Name</label>
<%= text_field :user, :first_name, :class => "input-block-level" %>
</div>
<div class="field">
<label>Last Name</label>
<%= text_field :user, :last_name, :class => "input-block-level" %>
</div>
<div class="field">
<label>Email</label>
<%= text_field :user, :email, :class => "input-block-level" %>
</div>
<div class="field">
<label>Role</label>
<%= text_field :user, :role_id, :value => 2 %>
</div>
</fieldset>
<fieldset>
<div class="field">
<label>Password</label>
<%= text_field :user, :password, :class => "input-block-level" %>
</div>
<div class="field">
<label>Confirm Password</label>
<%= text_field :user, :password_confirmation, :class => "input-block-level" %>
</div>
</fieldset>
<div class="form-actions">
<%= submit_tag 'Sign Up', :class => "btn btn-large btn-success btn-block" %>
</div>
<% end %>
My controller for the form is:
def signup
#company = Company.new
#user = #company.users.build
if #company.save
redirect_to :action => 'success'
else
render :action => 'signup'
end
end
When I save, it says that it fails.
This is the data that was posted (pasted from the rails console):
{"utf8"=>"✓", "authenticity_token"=>"9y4JeSvm34P05FBKbP3D3aToHlwejFZBkSyPbmGMJrk=", "company"=>{"name"=>"Test Co", "accounttype_id"=>"2"}, "user"=>{"first_name"=>"Andy", "last_name"=>"Bernard", "email"=>"andy#testco.com", "role_id"=>"2", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign Up"}
What is the form unable to save
is there a better way to do this process? (create new Company, then create user linked to that company, all in one form)
The signup action in your controller does not save #company because no attributes were passed when Company.new was called.
#company = Company.new(params[:company])
will pass the parameters "company"=>{"name"=>"Test Co", "accounttype_id"=>"2"}.
Likewise for "user"=>{...}:
#user = #company.users.build(params[:user])
For an all-in-one form, Rails provides the following method accepts_nested_attributes_for which allows you to create both the company and the user in one go.

form_for not rendering to view but is generating html correctly

I have the following form in my view:
<%= form_for #new_home, :url => {:controller => "homes", :action => "create"} do |f| %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.label :name, "Home Name:" %><br />
<%= f.text_field(:name) %>
<%= f.submit("Add New Home", :class => "green_button") %>
<% end %>
And controller:
def main
#new_home = Home.new
end
The generated html is:
<form accept-charset="UTF-8" action="/homes/create" class="new_home" id="new_home" method="post"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="lyvJq8FmFoOvzi7LYNhkrY8t9WI9phtBlNdGvMOFoF8=" />
<input id="home_user_id" name="home[user_id]" type="hidden" value="1" />
<label for="home_name">Home Name:</label><br />
<input id="home_name" name="home[name]" size="30" type="text" />
<input class="green_button" name="commit" type="submit" value="Add New Home" />
</form>
For some reason i cannot see the form being displayed in my view. There is no error generated. All i see is a blank page with no form. I have not applied any jquery or css to hide the form. Any thoughts?
I think you are missing the div field and action classes. See below.
<%= form_for #new_home, :url => {:controller => "homes", :action => "create"} do |f| %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<div class="field">
<%= f.label :name, "Home Name:" %><br />
<%= f.text_field :name %>
</div>
<div class="action">
<%= f.submit("Add New Home", :class => "green_button") %>
</div>
<% end %>
Let me know if it doesn't work!

Rails 3.2.1 nested attributes generating wrong output

HTML output generated code is wrong.
I have the following Post model
class Post < ActiveRecord::Base
belongs_to :user
attr_accessible :title, :description, :price, :status, :pageviews, :attachments_attributes
has_many :attachments, :as => :attachable
accepts_nested_attributes_for :attachments
validates :user_id, presence: true
validates :title, presence: true, length: { maximum: 50 }
validates :price, presence: true
validates :description, presence: true, length: { maximum: 1000 }
default_scope order: 'posts.created_at DESC'
end
my new.html.erb
<% provide(:title, "Novo anúncio")%>
<h1>Novo anúncio</h1>
<%= simple_nested_form_for #post, :html => { :multipart => true } do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class='field'>
<%= f.label "Título" %><br />
<%= f.text_field :title, size: 60, maxlength: 50 %>
</div>
<div class='field'>
<%= f.label "Descrição" %><br />
<%= f.text_area :description, cols: 100 %>
</div>
<div class='field'>
<%= f.label "Valor" %><br />
<%= f.text_field :price %>
</div>
<%= f.fields_for :attachments do |attachment_form| %>
<p><%= image_tag(attachment_form.object.file.url) if attachment_form.object.file? %></p>
<div class='field'>
<%= attachment_form.label :description %><br />
<%= attachment_form.text_area :description %>
</div>
<div class='field'>
<%= attachment_form.label :file %><br />
<%= attachment_form.file_field :file %>
</div
<%= attachment_form.link_to_remove "Remove this attachment" %>
<% end %>
<%= f.link_to_add "Add attachment", :attachments %>
<div class='actions'>
<%= f.submit "Enviar" %>
</div>
<% end %>
the code above is generating the following html:
<form accept-charset="UTF-8" action="/posts" class="simple_form new_post" enctype="multipart/form-data" id="new_post" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="7xO5QsSObfIO4A+FoKxCpFiqA5k3noIQBrpdwh2Iq2g=" /></div>
<div class='field'>
<label class="string optional control-label" for="post_Título"> Título</label><br />
<input id="post_title" maxlength="50" name="post[title]" size="60" type="text" />
</div>
<div class='field'>
<label class="string optional control-label" for="post_Descrição"> Descrição</label><br />
<textarea cols="100" id="post_description" name="post[description]" rows="20"></textarea>
</div>
<div class='field'>
<label class="string optional control-label" for="post_Valor"> Valor</label><br />
<input id="post_price" name="post[price]" size="30" type="text" />
</div>
Add attachment
<div class='actions'>
<input name="commit" type="submit" value="Enviar" />
</div>
</form><div id="attachments_fields_blueprint" style="display: none"><div class="fields">
<p></p>
<div class='field'>
<label class="text optional control-label" for="post_attachments_attributes_new_attachments_description"> Description</label><br />
<textarea cols="40" id="post_attachments_attributes_new_attachments_description" name="post[attachments_attributes][new_attachments][description]" rows="20"></textarea>
</div>
<div class='field'>
<label class="file optional control-label" for="post_attachments_attributes_new_attachments_file"> File</label><br />
<input id="post_attachments_attributes_new_attachments_file" name="post[attachments_attributes][new_attachments][file]" type="file" />
</div
<input id="post_attachments_attributes_new_attachments__destroy" name="post[attachments_attributes][new_attachments][_destroy]" type="hidden" value="false" />Remove this attachment
</div></div>
As you can see, the </form> is being called BEFORE the nested_attributes fields.
I have no clue what it's happening here.
Appreciate any help.
Can't tell for sure since you didn't post this part of your code, but in your controller's "new" action, make sure that you are
#post = Post.new
#post.attachments.build
The second line is important to setup a placefolder for the form to use.
Source: Problems with nested form fields showing up
The error was in the penultimate <div> tag that I missed to close.