Calling RSpec sleep - ruby

I'm writing a feature test right now that is trying test an edit action. It's a bit strange to me because it's not seeing what I expect when I run RSpec normally but when I use save_and_open_page command it shows that what I'm expecting is actually there in the browser. I think this is a selenium issue but I'm new to rspec and I'm not sure. I've been suggested to use "Sleep" or "Pause" but I'm not sure how to use these methods and I can't find any good docs on it. I'm wondering if someone can show me a valid way to use this on my current code?
TEST
require "rails_helper"
RSpec.feature "Edit 'Bounce Back' Message", :type => :feature do
given!(:group) { Group.create!(name: "Group A", response: "You are now subscribed for updates") }
scenario "Staff can see the response messages" do
visit "/groups"
user = FactoryGirl.create(:user)
fill_in "Email", with: user.email
fill_in "Password", with: user.password
click_button "Sign in"
expect(page).to have_content("You are now subscribed for updates")
expect(page).to have_content("Group a")
end
scenario "Staff can edit the response messages" do
visit "/groups/#{group.id}/edit"
user = FactoryGirl.create(:user)
fill_in "Email", with: user.email
fill_in "Password", with: user.password
click_button "Sign in"
expect(page).to have_content("You have now subscribed for updates")
end
end
I hope this is enough info please let me know if you need more. Thank You!
I've also tried using rspec_wait but it still is sending an error. here it is
<div class="container text-center">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 well">
<%= form_for #group do |form| %>
<div class="form-group">
<%= form.label :body, "Edit The Response:", class: "message_label"%>
<%= form.text_field :response, class: "form-control", placeholder: "New things are happening!" %>
</div>
<%= form.submit "Update", class: "btn btn-primary" %>
<% end %>
</div>
</div>
</div>

The currently accepted answer for this question is wrong. There is no need to use rspec-wait with Capybara matchers since they already have waiting/retrying behavior built in. You can adjust how long they wait/rety for using Capybara.default_max_wait_time, or passing a wait: <time in seconds> option to the matcher.
From reading the question and the attached image I assume the "Staff can see the response messages" test is passing but the "Staff can edit the response messages" test fails. If so it's most likely because on the edit page the "You have now subscribed for updates" string is actually the content of a field (textbox etc) rather than text content of the page. have_content is used for checking for text node content on the page, to test for a field with a given value you would use something like
expect(page).to have_field('Response', with: 'You have now subscribed for updates')
That assumes there is a label associated with the field with text of "Response", if not you can pass the id of the field, name, etc. or as of Capybara 2.7 you can pass nil and it will just look for any field with the given value - all depends exactly what you are needing to test for.
expect(page).to have_field(nil, with: 'You have now subscribed for updates')

Related

Why does the generated form's validation check the changeset's `:action` field instead of `:valid?`?

For example, issuing the
mix phx.gen.html Accounts User users name:string age:integer
command from the docs would generate form.html.eex:
<%%= form_for #changeset, #action, fn f -> %>
<%%= if #changeset.action do %>
<div class="alert alert-danger">
<p>Oops, something went wrong! Please check the errors below.</p>
</div>
<%% end %>
<%= for {label, input, error} <- inputs, input do %>
<%= label %>
<%= input %>
<%= error %>
<% end %>
<div>
<%%= submit "Save" %>
</div>
<%% end %>
Is there a reason for not checking #changeset.valid? == false instead?
The current form is indeed shorter, and it has been educational to learn that the :action key is nil only, when there has been no errors.
Is there any other consideration that one would need to take into account (e.g., adding more fields later), or this is just a matter of personal preference?
Somehow missed the Phoenix.HTML.Form documentation, where in the "A note on :errors" section it says that
If no action has been applied to the changeset or action was set to
:ignore, no errors are shown on the form object even if the changeset
has a non-empty :errors value.
This is useful for things like validation hints on form fields, e.g.
an empty changeset for a new form. That changeset isn’t valid, but we
don’t want to show errors until an actual user action has been
performed.
An empty changeset is indeed invalid by default:
iex> %Ecto.Changeset{}
#Ecto.Changeset<action: nil, changes: %{}, errors: [], data: nil, valid?: false>

simple-form not looking up i18n translations

simple-form is simply not looking up i18n translations. I was trying it on the placeholders.
simple_form.en.yml
en:
simple_form:
placeholders:
company:
name: "Company name"
The form:
<%= simple_form_for #company,
url: company_path(#company) do |f| %>
<div class="form-group">
<%= f.text_field :name, class: "form-control" %>
</div>
I've debugged using i18n-debug, and it didn't seem to attempt to look up
en.simple_form.placeholders.company.name
at all. Other non simple-form i18n lookups are triggering just fine.
Did I miss a step to 'turn on' i18n for simple-form? I thought it works right out of the box.
Looks like you are using text_field - a Rails form helper. Simple form supports it but it is not implemented in simple form (i.e. falls back to Rails). Change it to f.input :name and it should work.

Else part is not working in Rails ajax form

I have a Rails ajax form to submit.When user will give the correct data it will search the database and do the operation accordingly.If user is giving the Wrong data it should display user to alert message.But it is not happening like that.
I am explaining my codes below.
home.html.erb
<% if current_admin %>
<p class="flash-message"><%=flash[:notice]%></p>
<div class="col-md-6" style="float:none; margin:auto;">
<%= form_for :sdf ,:url => {:action => "scan_report" },remote: true do |f| %>
<% if params[:receipt_no] %>
<div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon text-left">Receipt No. Scan :</span>
<%= f.text_field :Receipt_No,:class => "form-control", :value => params[:receipt_no] %><%= f.submit "Scan Report" %>
</div>
<% else %>
<div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon text-left">Receipt No. Scan :</span>
<%= f.text_field :Receipt_No,:class => "form-control",placeholder:"Receipt No. scan" %><%= f.submit "Scan Report" %>
</div>
<% end %>
<% end %>
<% end %>
controller/homes_contorller.rb
class HomesController < ApplicationController
def home
#sdf=TSdf.new
respond_to do |format|
format.html
format.js
end
end
def scan_report
if #sdf=TSdf.find_by_Receipt_No(params[:sdf][:Receipt_No])
if #sdf && #sdf.HCSY_Status=='YES'
#hcsy=THcsy.find_by_Sdp_Id(#sdf.Sdp_Id)
#hcsy_deatils=THcsyDetails.find_by_HCSY_ID(#hcsy.id)
#woods=THcsyFundTypeMaster.find_by_Fund_Type_Code(1)
#burn=THcsyFundTypeMaster.find_by_Fund_Type_Code(2)
#good=THcsyFundTypeMaster.find_by_Fund_Type_Code(3)
#swd=THcsyFundTypeMaster.find_by_Fund_Type_Code(5)
#photo=THcsyFundTypeMaster.find_by_Fund_Type_Code(6)
end
else
flash[:notice]="Not Found"
end
end
end
In this form its only taking the correct input but if user is trying to give the wrong input the else part is not executing.Please help me to resolve this error and let me to know how can i make this ajax call in below format.
$('form').submit(function() {
var valuesToSubmit = $(this).serialize();
$.ajax({
type: "POST",
url: $(this).attr('action'), //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
}).success(function(json){
console.log("success", json);
});
return false; // prevents normal behaviour
});
Please help me.I am using Rails version 3.2.19.
Here you send AJAX POST request to scan_report, and if it is successful it should render template scan_report.js.erb, and rendered template will appear in json variable in success callback.
But if params are not valid, the same template is rendered, but all instance variables are missing. And probably empty json is returned or an error appears in log.
Anyway, if you'd like to change flash in remote form, you should put custom code in fail callback. Something like
$("#flash").html('<%= j render flash[:notice] %>');

Devise with multiple models, bootstrap modal with ajax login

I have 2 kinds of users - nurses and patients, and want to setup login such that there are two buttons on the welcome/landing page which open up a bootstrap modal with the login form for each type of user. I'd like the login form to send an AJAX request so that if there are errors, they are displayed in the modal itself.
I'm using Devise for authentication, and have setup 2 models for nurses and patients. Initially, I setup the modal to load the url for the new_nurse_session_path on clicking the button, modified the default devise login form to send AJAX requests, used a custom SessionsController to handle new sessions and send JSON replies back, and then have JS code which catches the reply. This worked (though with some issues as below) was pretty slow since it was loading the entire page from nurses/sessions/new.html.erb along with the header, navbar, etc.
Questions
While the JS code was catching the AJAX request when the entire sign in page was opened in the modal (as per code below), if I opened the page directly, the AJAX request wasn't processed even though the server was sending the correct JSON back - is there something I'm doing wrong here that might be causing this problem?
To avoid the entire new session page from being loaded in the modal, I followed the instructions here https://github.com/plataformatec/devise/wiki/How-To:-Display-a-custom-sign_in-form-anywhere-in-your-app to put the form in the modal. The issue I'm facing here is how to create the helper so that it defines the resource and Devise mappings according to whether it's a nurse or patient trying to login. If I create separate custom forms and modals for each one, I face the same issue with handling AJAX requests as in Q1. Would really appreciate help on what I might be doing wrong here.
If I'm going down a rabbit hole here, would really appreciate suggestions on implementing the above functionality in a better way! Thanks!
Code used
Login form, nurses/sessions/new.html.erb:
<%= form_for(resource, :as => resource_name, :url => session_path(resource_name),
:html => {:id => "sign_in_nurse"}, :format => :json,
:remote => true) do |f| %>
<div><%= f.label :email %><br />
<%= f.email_field :email, :autofocus => true %></div>
<div><%= f.label :password %><br />
<%= f.password_field :password %></div>
<% if devise_mapping.rememberable? -%>
<div><%= f.check_box :remember_me %> <%= f.label :remember_me %></div>
<% end -%>
<div><%= f.submit "Sign in" %></div>
<% end %>
<%= render "nurses/shared/links" %>
Coffeescript to handle AJAX reply, nurses.js.coffee:
$("form#sign_in_nurse").bind "ajax:success", (e, data, status, xhr) ->
if data.success
window.location.replace(data.redirect)
else
alert('failure!')
SessionsController:
class SessionsController < Devise::SessionsController
def create
resource = warden.authenticate!(:scope => resource_name, :recall => "sessions#failure")
return sign_in_and_redirect(resource_name, resource)
end
def sign_in_and_redirect(resource_or_scope, resource=nil)
scope = Devise::Mapping.find_scope!(resource_or_scope)
resource ||= resource_or_scope
sign_in(scope, resource) unless warden.user(scope) == resource
return render :json => {:success => true, :redirect => stored_location_for(scope) || after_sign_in_path_for(resource)}
end
def failure
return render :json => {:success => false, :errors => ["Login failed."]}
end
end
Code to generate modal:
<li><%= link_to image_tag('i_am_nurse.png', :size => "130x130"),
new_nurse_session_path , :data => { :target => "#ajax-modal", :toggle => "modal"} %></li>
Bootstrap modal div:
<div id="ajax-modal" class="modal hide fade" tabindex="-1">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="modal-body-content"></div>
<div class="ajax-loader"></div>
</div>
<div class='modal-footer'>
<button type="button" data-dismiss="modal" class="btn">Close</button>
</div>
</div>​

RoR: How can I get my microposts to show up?

Here is the users show view where they are supposed to show up. ..
<section>
<div id= "purchases">
<%= render 'shared/micropost_form_purchase' %>
</div>
<div id="sales">
<%= render 'shared/micropost_form_sale' %>
</div>
</section>
<%= #sales %> <%# This is just to see if it outputs anything. It doesn't :( %>
<div id="purchases list">
<ol class="microposts">
<%= render #purchases unless #purchases.nil? %>
</ol>
</div>
<div id="sales list">
<ol class="microposts">
<%= render #sales unless #sales.nil? %>
</ol>
</div>
so the forms (partials) are loading fine, but then when I make a post, in either one, neither the purchases list nor the sales list shows up. I checked the database and they are being created along with an entry in the column indicating kind (either sale or purchase).
Here are the forms:
<%= form_for (#micropost) do |f| %>
<div class="field no-indent">
<%= f.text_area :content, placeholder: "What's something else you want to buy?" %>
<%= hidden_field_tag 'micropost[kind]', "purchase" %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
and
<%= form_for (#micropost) do |f| %>
<div class="field no-indent">
<%= f.text_area :content, placeholder: "What's something else you want to buy?" %>
<%= hidden_field_tag 'micropost[kind]', "sale" %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
also, here is the show part of the users_controller.rb
def show
#user = User.find(params[:id])
#micropost=Micropost.new
#microposts = #user.microposts.paginate(page: params[:page])
end
and here is the show part of the microposts_controller.rb
def show
#micropost = Micropost.find(params[:id])
#microposts = Micropost.where(:user_id => #user.id)
#purchases= #microposts.collect{ |m| m if m.kind == "purchase"}.compact
#sales = #microposts.collect{ |m| m if m.kind == "sale"}.compact
end
additionally, with the help of this post (http://stackoverflow.com/questions/12505845/ruby-error-wrong-number-of-arguments-0-for-1#12505865) the variables #microposts, #purchases, and #sales are all outputting correctly in the console.
can anyone help me out?
edit: using scopes as suggested by the answer given works in the console (it outputs everything correctly, but they still don't show up in the view. Does this mean it is something wrong with my syntax for the users show page?
edit 2:
Here is the view/microposts/_micropost.html.erb code
<li>
<span class="content"><%= micropost.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(micropost.created_at) %> ago.
</span>
<% if current_user?(micropost.user) %>
<%= link_to "delete", micropost, method: :delete,
confirm: "You sure?",
title: micropost.content %>
<% end %>
</li>
I'm making some assumptions without seeing more of your code, but it looks like you could
write what you've shown a little differently. I'm assuming your databases are migrating
and have the required columns, e.g., Micropost#kind, Micropost#user_id, etc.
You can use scopes to refine a collection of microposts more expressively. It might be helpful to read
up about ActiveRecord scopes: http://guides.rubyonrails.org/active_record_querying.html#scopes.
class Micropost < ActiveRecord::Base
belongs_to :user
scope :purchases, where(:kind => "purchase")
scope :sales, where(:kind => "sale")
# your code
end
I'm also assuming your user has many microposts:
class User < ActiveRecord::Base
has_many :microposts
# your code
end
For your forms, I'd suggest attaching your hidden field to the form object (f.hidden_field) so
you don't have to specify the name as 'micropost[kind]'.
<%= form_for(#micropost) do |f| %>
<div class="field no-indent">
<%= f.text_area :content, placeholder: "What's something else you want to buy?" %>
<%= f.hidden_field :kind, :value => "sale" %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
In MicropostsController#show, you can use your new scopes:
def show
#micropost = Micropost.find(params[:id])
#microposts = #user.microposts
#purchases = #microposts.purchases
#sales = #microposts.sales
end
You should also confirm that your MicropostsController#create action is actually adding
the microposts to the user sending the form (I'm assuming a current user method).
def create
#micropost = current_user.microposts.create(params[:micropost])
# yada
end
You can also confirm expected results on rails console after creating purchases or sales micropost with:
Micropost.purchases
Micropost.sales
Again, I could be missing something without seeing more of the code base.
Check Micropost.count, #purchases.count, #sales.count (by printing them in the controller, or some part of the view) to see if the records actually exist.
Also, if you want to render collections likes #sales and #purchases, you need to make sure that the model partial exists (_micropost.html.erb in your case). That is probably where you need to look for the view errors. For all you know, that file could be empty, thus no errors will show up at all.
The problem might also lie in your microposts#create (or whichever action that you are saving the micropost in), the micropost should be associated with the current_user:
#micropost = current_user.microposts.build(params[:micropost])
Taking this and your previous question into account, I suggest you go through the original code for the RoR tutorial again (and verify that all tests are passing) before taking it apart. You can always add new tests to it for your experiments and they will help in figuring out where you went wrong.

Resources