Why would this functional test be failing? - ruby-on-rails

My haml :
- for status in current_account.job_statuses.active
= link_to status.name, '#', :class => params[:job_status_id].to_i == status.id ? "current status block" : "status block", :rel => status.id
My html :
<a rel="1" class="status block" href="#">in progress</a>
<a rel="2" class="status block" href="#">in progress</a>
<a rel="3" class="status block" href="#">in progress</a>
<a rel="4" class="status block" href="#">in progress</a>
My Test :
test 'index - job_status: set' do
job_status = #account.job_statuses.create! :name => 'foo'
job_status.reload
#job.update_attribute :job_status_id, job_status.id
#job.reload
get :index, :job_status_id => job_status.id.to_s
assert_response :success
assert_template 'jobs/index'
jobs = assigns(:jobs)
assert jobs.include?(#job)
assert_select 'div.status[rel=?]', job_status.id
end
But I get this failure :
3) Failure:
test_index_-_job_status:_set(NewJobsControllerTest)
[test/functional/new_jobs_controller_test.rb:127:in `block in <class:NewJobsControllerTest>'
test/test_helper.rb:221:in `run'
test/test_helper.rb:221:in `run']:
Expected at least 1 element matching "div.status[rel='16']", found 0.
<false> is not true.
Is this for an obvious dumb reason? I apologize if it is.. I can't figure it out.

Oh. It's always the little things we never think to check... After staring uselessly at that HAML I asked for for five minutes it hit me:
Those ain't DIVs. Those are As.
Cheers!

Related

asserting value of selector

The following Minitest snippet
puts response.body.inspect
# assert response.body.include?("Log out of all other sessions")
assert_select "input[type='submit']" do
assert_select "[value=?]", "Log out of all other sessions"
end
is failing as Expected at least 1 element matching "[value="Log out of all other sessions"]", found 0..
Yet the inspection has the following string:
<form class=\"button_to\" method=\"post\" action=\"/active_sessions/destroy_all\">
<input type=\"hidden\" name=\"_method\" value=\"delete\" autocomplete=\"off\" />
<button type=\"submit\">Log out of all other sessions</button>
</form>
The value in the view is set via i18n:
<%= button_to t('user.auth.session_delete_all'), destroy_all_active_sessions_path, method: :delete %>
uncommenting assert response.body.include?("Log out of all other sessions") asserts.
How should the failing assertion be cast?

Rails, Capybara - click_link on remote links doesnt work

I'm using Capybara to test my project. But i have a problem.
I have some remote forms on my project. They add records via ajax. When i'm testing with capybara it works well on development environment. It visits the page, fills in the form and submits. Booom, record has been added and test didnt fail.
But when i run rspec with test environments i'm getting unknown format exception.
1) add new address user adds new address
Failure/Error: find("input[value='Adres Ekle']").click
ActionController::UnknownFormat:
Account::AddressesController#create is missing a template for this request format and variant.
request.formats: ["text/html"]
request.variant: []
# ./spec/features/user_add_new_address_spec.rb:28:in `block (2 levels) in <top (required)>'
I've also tried to respond via js from controller like;
def create
request.format = :js
end
Then it returns;
1) add new address user adds new address
Failure/Error: find("input[value='Adres Ekle']").click
ActionController::UnknownFormat:
Account::AddressesController#create is missing a template for this request format and variant.
request.formats: ["text/javascript"]
request.variant: []
# ./spec/features/user_add_new_address_spec.rb:28:in `block (2 levels) in <top (required)>'
And my scenario if u want more info;
scenario 'user adds new address' do
expect(page).to have_content 'Kayıtlı Adreslerim'
find("a[title='Adres Ekle']").click
expect(page).to have_content 'Yeni Adres Ekle'
expect(page).to have_content 'Adres Başlığı'
fill_in 'address[name]', with:'Izmir Ofisi'
select('Izmir', :from => 'address[city_id]')
fill_in 'address[address]', with: 'Lorem ipsum dolor sit amet.'
find("input[value='Adres Ekle']").click # It submits remote: true form.
expect(page).to have_content 'Success!'
end
PS: my create action doesnt render something like that.
its like;
def create
#new_address = Address.new
#address = #current_account.addresses.new(address_params)
if #address.save
#check = true
else
#check = false
end
end
it renders: create.js.erb
<% if #check %>
if($('.addresses').length) {
$('.addresses').append('<%= j(render('account/addresses/address', address: #address)) %>');
}
if($('#did-addresses').length){
$('#did-addresses').append("<%= "<option selected='true' value='#{#address.id}'>#{#address.name}</option>".html_safe %>").selectpicker('refresh');
}
$('#new-address').html('<%= j(render('account/addresses/form', new_address: #new_address)) %>');
swal({
type: 'success',
title: "<%= t('response.success') %>",
text: "<%= t('flash.actions.create.notice', resource_name: Address.model_name.human) %>",
timer: 2000
});
quickview.close('#new-address');
<% else %>
<% #address.errors.each do |error| %>
<% end %>
<% end %>
$('.preloader').fadeOut();
I was facing the same case in rails 6 but I fixed it be adding js: true to the scenario and it automatically worked well.
scenario 'Should delete the feature', js: true do
# Your logic
# Your expectations
end
Since copying your development config over your test config fixed your issue, it sounds like you probably an error in one of your JS files. Normally in the test and production environment all of your JS assets get concatenated into one file which means an error in any one of them can prevent the code in the others from being executed. In the development environment each JS file is loaded separately which means an error in any file can only affect the rest of the code in that file. Check your the console in your browser for any JS errors when going to the page in question and fix them.

Capybara not finding signout link by id

For a rails app I'm currently working on I recently changed the design somewhat so that the signout link no longer has the anchor text "Sign out" but instead a glyphicon from twitter bootstrap. the html for link now looks like this:
<a class="btn btn-primary btn-sm" data-method="delete" href="/users/sign_out" rel="nofollow">
<span class="glyphicon glyphicon-log-out"></span>
</a>
meanwhile my capybara test looks like this:
context "when not logged in" do
it 'cannot create wikis' do
#free_user = create(:user)
login_as(#free_user, :scope => :user)
click_link "Sign out"
visit root_path
expect(page).to_not have_link('Create wiki')
end
end
Now that the text "Sign out" is no longer there, I need a new way to identify the link. Checking the documentation for capybara (or rather this handy cheatsheet), it looks like I can supply either the text of the link or its id. So I tried giving it an id:
<a class="btn btn-primary btn-sm" data-method="delete" href="/users/sign_out" id="signout" rel="nofollow">
<span class="glyphicon glyphicon-log-out"></span>
</a>
So now it's got an id of "signout" however when I make this change to the test, it still won't pass.
1) Standard (free) User when not logged in cannot create wikis
Failure/Error: click_link "signout"
Capybara::ElementNotFound:
Unable to find link "signout"
# ./spec/features/standard_user_role_spec.rb:107:in `block (3 levels) in <top (required)>'
I tried making sure that I was still a logged in user in the test by creating and logging in the user as seen above and by adding a check that the html on the page contains Hello, since it says "Hello" and the name of the user when the user is logged in:
expect(page).to have_content('Hello')
This gave me another error that I don't understand:
1) Standard (free) User when not logged in cannot create wikis
Failure/Error: expect(page).to have_content('Hello')
Capybara::ElementNotFound:
Unable to find xpath "/html"
# ./spec/features/standard_user_role_spec.rb:107:in `block (3 levels) in <top (required)>'
So what could be going on here?
Full spec available here
You can re-add the text but hide it from all but screen readers:
<a class="btn btn-primary btn-sm" data-method="delete" href="/users/sign_out" id="signout" rel="nofollow">
<span class="sr-only">Sign out</span>
<span class="glyphicon glyphicon-log-out"></span>
</a>
This also improves accessibility somewhat.
context "when not logged in" do
it 'cannot create wikis' do
#free_user = create(:user)
login_as(#free_user, :scope => :user)
visit root_path
click_link "Sign out", visible: false
expect(page).to_not have_link('Create wiki')
end
end
Note that we explicitly tell Capybara to look for hidden text with the visible option.
For the applications, which use JS, that means the request is being sent using for example json format, and is begin triggered by click on the link. (suppose the HTML markup is the same). It is useful the following call:
find('Sign Out', visible: false).trigger('click')
or by id (if you'll add it):
find(:css, "#sign-out", visible: false).trigger('click')

Rails: Capybara doesn't find a div element

I'm using Capybara with RSpec to check my Rails project.
I'm testing errors when form fields are not correctly filled. Here is the form (using haml):
= form_tag '/objects', :class => 'objects-form' do
%ul
%li= select_tag 'object', options_for_select([['Select an object', ''], ['Car', 'CAR'], ['Keys', 'KEYS'], ['Ambrella', 'AMBRELLA']]), :id => 'select-object'
%li= text_field_tag :quantity, nil
%li= submit_tag 'Buy', :id => 'object-submit'
When an error occurs (in this case, not choosing an object but only a quantity), a flash message is displayed (with a .flash-error class name):
- flash.each do |type, msg|
= content_tag :div, msg, :class => "flash-#{type}", :id => 'flash-msg'
So, here is my Capybara test:
it 'Should return error when no object selected' do
within 'form.objects-form' do
fill_in 'quantity', :with => '1'
click_button 'object-submit'
current_path.should == objects_path
save_and_open_page
page.should have_css 'div.flash-error'
end
end
But I get the following Capybara error:
Failure/Error: page.should have_css 'div.flash-error'
expected #has_css?("div.flash-error") to return true, got false
The opened page (using save_and_open_page) shows the error message with the appropriate div:
div#flash-msg.flash-error
I'm using the latest version of Capybara (since many similar problems on Stackoverflow are relative to old versions of Capybara) using gem 'capybara', :git => 'https://github.com/jnicklas/capybara.git'
Any idea? Thank in advance.
EDIT:
Corrected typing mistake on Capybara code, as detected by Alex.
The problem is your selector you are using in capybara is div#flash-error but your div is div#flash-msg.flash-error or more simply div.flash-error.

Cucumber `press button` failure (Capybara::ElementNotFound)

I'm a relative newbie starting up a new Ruby on Rails app. I started by following a combination of instructions at https://github.com/intridea/omniauth, http://www.communityguides.eu/articles/16, http://intridea.com/2011/1/31/easy-rails-admin-login-with-google-apps-and-omniauth?blog=company . At the point everything appeared to work correctly, I started to write my very first cucumber features and steps. I was able to get a couple of steps up and running, but I've been bogged down on a step that I thought was built in. I have a form with two submit_tags but I can't get a scenario to successfully pass a basic And I press "button" step.
possibly relevant gems:
rails (3.1.0.rc4)
capybara (1.0.0)
cucumber (1.0.1)
cucumber-rails (1.0.2)
nokogiri (1.4.7)
gherkin (2.4.5)
rack-test (0.6.0)
selenium-webdriver (0.2.2)
section of the form in question:
<%= form_tag :controller => "services", :action => "newaccount" do %>
<%= submit_tag "confirm", :id => "confirm", :title => "confirm", :value => "confirm", :text => "confirm", :name => "confirm" %>
<%= submit_tag "cancel", :id => "cancel", :title => "cancel", :value => "cancel", :text => "cancel", :name => "cancel" %>
<% end %>
scenario in question:
Scenario: I register with a valid and currently active google account
Given I am not registered
When I sign in with a valid and currently active google account
And I press "confirm" # <-- THE PROBLEMATIC STEP
Then I should see "Your account has been created and you have been signed in!"
I think this is the relevant web_step (straight from the default web_steps.rb which I have not edited at all):
When /^(?:|I )press "([^"]*)"$/ do |button|
click_button(button)
end
relevant cucumber output:
Scenario: I register with a valid and currently active google account # features/auth_and_auth/initial_tests.feature:6
Given I am not registered # features/step_definitions/authentication_steps.rb:1
When I sign in with a valid and currently active google account # features/step_definitions/authentication_steps.rb:5
And I press "confirm" # features/step_definitions/web_steps.rb:52
no button with value or id or text 'confirm' found (Capybara::ElementNotFound)
(eval):2:in `click_button'
./features/step_definitions/web_steps.rb:53:in `/^(?:|I )press "([^"]*)"$/'
features/auth_and_auth/initial_tests.feature:9:in `And I press "confirm"'
Then I should see "Your account has been created and you have been signed in!" # features/step_definitions/web_steps.rb:105
relevant html output:
<input id="confirm" name="confirm" text="confirm" title="confirm" type="submit" value="confirm">
<input id="cancel" name="cancel" text="cancel" title="cancel" type="submit" value="cancel">
As is obvious, I've accounted for value, id, text, as well as name and title. I also saw a post that said the input type had to be specified as submit which it appears to have been. And I've tried it with both the confirm button and the cancel button.
After searching everywhere that I know about, and trying every suggestion that looked even remotely relevant, I'm at an impasse. What am I missing?
I'm not sure if the code below is the best way to deal with the problem I encountered, but it is getting the relevant step to pass.
When /^(?:|I )press "([^"]*)"$/ do |button|
# click_button(button) # the original web_steps.rb version that fails
%{I press (button)} # my revised version that passes
end
I'd still appreciate any feedback on:
why the original web_steps.rb version fails,
whether this is an appropriate approach or not, and
if there is a more 'rails' way to deal with this.

Resources