assert_select not working in test - ruby-on-rails

I've scoured the internet for an answer and found nothing... this is driving me insane!
No assert_select statements are working in any of my tests. I've repeatedly confirmed that the element is actually in the dom on the targeted page — and it is — but every test fails on an assert_select statement. Even one as general as assert_select 'body'!
Here's one test:
require 'test_helper'
class UsersIndexTest < ActionDispatch::IntegrationTest
def setup
#user = users(:matt)
end
test "index including pagination" do
log_in_as(#user)
get users_path
assert_template 'users/index'
assert_select 'div.pagination'
User.paginate(page: 1).each do |user|
assert_select 'a[href=?]', user_path(user), text: user.first_name
end
end
end
Here's users/index.html.haml
%h1 All Users
= link_to 'New User', new_user_path
= will_paginate
%table
%thead
%tr
%th
%th First name
%th Last name
%th Email
%th
%th
%th
%tbody
- #users.each do |user|
%tr
%td= gravatar_for(user)
%td= user.first_name
%td= user.last_name
%td= user.email
%td= link_to 'Show', user
%td= link_to 'Edit', edit_user_path(user)
%td= link_to 'Destroy', user, :method => :delete, :data => { :confirm => 'Are you sure?' }
= will_paginate
Pretty boring stuff, right? And yet, the test fails:
FAIL["test_index_including_pagination", UsersIndexTest, 0.9574]
test_index_including_pagination#UsersIndexTest (0.96s)
Expected at least 1 element matching "div.pagination", found 0..
Expected 0 to be >= 1.
test/integration/users_index_test.rb:12:in `block in <class:UsersIndexTest>'
Even when I change the assertion to assert_select div, it fails. And, again, I can confirm that the div is present when I visit the index page.
What am I missing here!?!?!?!
If it helps, here's my gemfile:
source 'https://rubygems.org'
gem 'rails', '4.2.0'
gem 'pg'
gem 'puma'
gem 'turbolinks'
gem 'jquery-rails'
gem 'bcrypt', '~> 3.1.7'
gem 'faker', '~> 1.4.2'
gem 'sass-rails', '~> 5.0.1'
gem 'bootstrap-sass', '~> 3.2.0'
gem 'will_paginate', '~>3.0.7'
gem 'bootstrap-will_paginate','~>0.0.10'
gem 'uglifier', '>= 2.5.0'
gem 'haml-rails', '~> 0.8'
gem 'jbuilder', '~> 2.2.3'
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'rest-client', '~> 1.7.3'
gem 'bourbon'
group :development, :test do
gem 'byebug'
gem 'web-console', '~> 2.0.0'
gem 'spring'
gem 'better_errors'
end
group :test do
gem 'minitest-reporters', '~> 1.0.5'
gem 'mini_backtrace', '~> 0.1.3'
gem 'guard-minitest', '~> 2.3.1'
end
group :production do
gem 'rails_12factor'
end
ruby '2.2.0'
Thanks to Steve Klein for the suggestion of printing out the response body. Unfortunately, the plot only thickens. The body clearly has the tag I'm targeting!
Added a line to the above test
assert_template 'users/index'
puts #response.body
assert_select 'div.pagination'
And the output has the tag!
← Previous 1 2 Next →
And yet still fails!!!
FAIL["test_index_as_admin_including_pagination_and_delete_links", UsersIndexTest, 1.412393] test_index_as_admin_including_pagination_and_delete_links#UsersIndexTest (1.41s)
Expected at least 1 element matching "div.pagination", found 0..
Expected 0 to be >= 1.
test/integration/users_index_test.rb:15:in `block in <class:UsersIndexTest>'

Make sure you are loading enough test data to trigger pagination. This selector won't be on your page unless pagination kicks in (depends on how you have configured will_paginate in your controller action).

It might be that the problem lies in line 13: User.paginate(page: 1).each do |user|. Try commenting the loop or cutting it out and run the test again. If it succeeds now, it could be that you have changed the default pagination method in your /users_controller.rb file. Try matching your custom pagination method with the one in your integration test. Something like the following for example: User.paginate(page: 1, per_page: 10).each do |user|

I had same problem with assert_select 'div.pagination', so I cought this thread googling the error.
I read the thread and got back to my app.
I tried to test:
assert_select 'div'
which passed.
I then switched back to:
assert_select 'div.pagination'
and test passed as well :O
For your reference, this is my users_index_test.rb
require 'test_helper'
class UsersIndexTest < ActionDispatch::IntegrationTest
def setup
#user = users(:archer)
end
test "index including pagination" do
log_in_as(#user)
get users_path
assert_template 'users/index'
assert_select 'div.pagination'
User.paginate(page: 1).each do |user|
assert_select 'a[href=?]', user_path(user), text: user.name
end
end
end
and this is my fixture users.yml
michael:
name: Michael Example
email: michael#example.com
password_digest: <%= User.digest('password') %>
archer:
name: Sterling Archer
email: duchess#example.gov
password_digest: <%= User.digest('password') %>
lana:
name: Lana Kane
email: hands#example.gov
password_digest: <%= User.digest('password') %>
mallory:
name: Mallory Archer
email: boss#example.gov
password_digest: <%= User.digest('password') %>
<% 30.times do |n| %>
user_<%= n %>:
name: <%= "User #{n}" %>
email: <%= "user-#{n}#example.com" %>
password_digest: <%= User.digest('password') %>
<% end %>
I really don't know why now it pass, but I wanted to contribute in the research of a more logical solution.

Double check your fixture file for typos and make sure that you are indeed loading enough comments to trigger inclusion of a pagination.
I had the same problem as you, originating from chapter 13 of the Ruby on Rails Tutorial. I included 'puts response.body' in my test and discovered that the ERb comments that I attempted to generate in my "comments.yml" were not being generated during the test. The issue turned out to be that I forgot a single '=' sign in an ERb tag. Hopefully for you the solution is equally simple!

For whoever runs into this problem in the future, knowing fully well you tried all of the solutions above and nothing changed.
Pay attention to this line in the users.yml file
Wrong:
<% 30.times do |n| %>
user_<%= n %>:
name: <%= "User #{n}" %>
email: <%= "user-#{n}#example.com" %>
password_digest: <%= User.digest('password') %>
<% end %>
Wrong:
<% 30.times do |n| %>
user_<%= n %>:
name: <%= "User #{n}" %>
email: <%= "user-#{n}#example.com" %>
password_digest: <%= User.digest('password') %>
<% end %>
Correct:
<% 30.times do |n| %>
user_<%= n %>:
name: <%= "User #{n}" %>
email: <%= "user-#{n}#example.com" %>
password_digest: <%= User.digest('password') %>
<% end %>

Related

Rails link do not work in Trailbalzer::cell

I am using cell to render Navigation Bar for current_user devise. But went i try to render page i get an error. I am using rails 7 and ruby 3.0.2
Error
undefined method `new_user_session_path' for #<Navigation::Cell::Show:0x00007fac566e3570 #model=#<User id: 1, email: "email#gmail.com", first_name: "Otto", last_name: "Otto", phone: nil, birthday: nil, gender: nil, city: nil, street: nil, house: nil, apartment: nil, created_at: "2023-01-07 18:10:10.925669000 +0000", updated_at: "2023-01-07 18:30:10.207258000 +0000">, #options={}>
My application.html.erb
<body>
<%= Navigation::Cell::Show.(current_user) %>
<%= yield %>
</body>
Gemfile
gem 'trailblazer-cells', '~> 0.0.3'
gem 'trailblazer-rails', '~> 2.4', '>= 2.4.3'
gem 'cells-erb', '~> 0.1.0'
Navigation::Cell:Show (app/concepts/navigation/cell/show.rb)
class Navigation::Cell::Show < Trailblazer::Cell
include Devise::Controllers::Helpers
include ActionView::Helpers::UrlHelper
include Cell::Erb
def show
render
end
private
def username
"#{model.first_name} #{model.last_name}"
end
def current_user
model
end
def profile_link
link_to username, new_user_session_path(current_user.id)
end
def logout_link
link_to 'Log Out', destroy_user_session_path, method: :delete
end
def login_link
link_to 'Login', new_user_session_path
end
def registration_link
link_to 'Registration', new_user_registration_path
end
end
And my view (app/concepts/navigation/view/show.erb)
<nav>
<div>
<% if current_user %>
<h1><%= profile_link %></h1>
<%= logout_link %>
<% else %>
<%= login_link %>
<%= registration_link %>
<% end %>
</div>
</nav>
I try to include include ActionView::Helpers::UrlHelper it didn`t work.
When i add gem gem 'cells-rails' to rails app i have another error that looks like this
error
Your error
undefined method `new_user_session_path'
This method is from routes URL helpers (named route helper)
You need this line additionally:
include Rails.application.routes.url_helpers

Rails google-oauth2 404 - "Not found. Authentication passthru."

When attempting to sign in with Google Oauth, I encounter a 404 error "Not found. Authentication passthru." This worked just a month ago on my site, and I have not changed anything that should have impacted authentication. I've seen several other posts about this, but none have seemed to work in my case.
initializers/devise.rb
Devise.setup do |config|
config.omniauth :google_oauth2, ENV['GOOGLE_OAUTH_CLIENT_ID'], ENV['GOOGLE_OAUTH_CLIENT_SECRET']
.
.
.
gemfile
gem 'devise', github: 'heartcombo/devise'
gem 'omniauth', '~> 1.6', '>= 1.6.1'
gem 'omniauth-google-oauth2'
gem "omniauth-rails_csrf_protection"
routes.rb
devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }
devise_scope :user do
get 'users/sign_in', to: 'users/sessions#new'
get 'users/sign_out', to: 'users/sessions#destroy'
end
view
<%- if devise_mapping.omniauthable? %>
<%- resource_class.omniauth_providers.each do |provider| %>
<% if provider = "google_oauth2" %>
<%= link_to "Sign in with Google", omniauth_authorize_path(resource_name, provider), method: :post, class: "oauth-link" %><br />
<% else %>
.
.
.
I was hitting this myself and thought the 404 was some kind of error. I believe it's the intended response when the Omniauth controller doesn't recognize the provider. Try:
<%= link_to "Sign in with Google", user_google_omniauth_authorize_path, method: :post, class: "oauth-link" %>
If you're using Turbo, you'll want to change it to a button_to and set data-turbo: false.

Rails/devise app not working properly on Heroku due to new_user_registration_path

Hope one of you can help me out on this one, since I've been breaking my head on it for a while.
I deployed my app to Heroku after trying it out on the cloud9 preview.
The problem is that whenever I try to press the button to create a account for a paid subscription, I don't get linked to the page to fill in my credentials. However, on cloud9 this seems to be working fine.
I found the the sole difference between the two by hovering over the same buttons on the different platforms with my mouse.
On cloud9 I get: https://xxxxxxxx-xxxxx.xxxxxxx.xx/users/sign_up?plan=1
On Heroku I get: https://xxxxxxxx-xxxx-xxxxx.herokuapp.com/sign_up
So whenever I click the one on Heroku, I get my build-in flash message saying: Please select a membership plan to sign up!
To be more specific whereas the problem lies according to me, I think it's somewhere in the home.html.erb where the variable gets passed through. (added below)
So it seems that the routing isn't working correct on my Heroku, but I just can't figure out why. I've added my files below.
Hope someone can help me out on this one!
Kind regards.
Gemfile
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.5'
# Use sqlite3 as the database for Active Record
gem 'sqlite3', group: [:development, :test]
# Use postgresql as the database for production
group :production do
gem 'pg'
gem 'rails_12factor'
end
# Use SCSS for stylesheets
gem 'sass-rails', '~> 5.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .coffee assets and views
gem 'coffee-rails', '~> 4.1.0'
# See https://github.com/rails/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
# gem 'bcrypt', '~> 3.1.7'
# Use Unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug'
end
group :development do
# Access an IRB console on exception pages or by using <%= console %> in views
gem 'web-console', '~> 2.0'
# Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
gem 'spring'
end
### ADDED GEMS ###
# Bootstrap Gem
gem 'bootstrap-sass', '~> 3.3.6'
# Devise Gem
gem 'devise'
# Font Awesome
gem 'font-awesome-rails'
# Use stripe for handling payments
gem 'stripe'
# Use figaro to hide secret keys
gem 'figaro'
ruby '2.3.0'
routes.rb
Rails.application.routes.draw do
devise_for :users, controllers: { registrations: 'users/registrations' }
resources :users do
resource :profile
end
resources :contacts
get '/about' => 'pages#about'
root 'pages#home'
end
pages_controller.rb
class PagesController < ApplicationController
def home
#trial_plan = Plan.find_by id: '1'
#pro_plan = Plan.find_by id: '2'
end
def about
end
end
users/registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
before_filter :select_plan, only: :new
def create
super do |resource|
if params[:plan]
resource.plan_id = params[:plan]
if resource.plan_id == 2
resource.save_with_payment
else
resource.save
end
end
end
end
private
def select_plan
unless params[:plan] && (params[:plan] == '1' || params[:plan] == '2')
flash[:notice] = "Please select a membership plan to sign up."
redirect_to root_url
end
end
end
application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Ayris</title>
<%= stylesheet_link_tag 'application', media: 'all' %>
<%= javascript_include_tag "https://js.stripe.com/v2/", type: 'text/javascript' %>
<%= javascript_include_tag 'application' %>
<%= tag :meta, :name => "stripe-key", :content => STRIPE_PUBLIC_KEY %>
<%= csrf_meta_tags %>
</head>
<body>
...
<%= link_to root_path, class: 'navbar-brand' do %>
<i class="fa fa-users"></i>
Ayris
<% end %>
...
<% if user_signed_in? %>
...
<% else %>
...
<% if user_signed_in? %>
...
<% end %>
<li><%= link_to "About", about_path %></li>
<li><%= link_to "Contact Us", new_contact_path %></li>
</ul>
</div><!-- /.navbar-collapse -->
</div>
</nav>
<div class="container">
<% flash.each do |key, value| %>
<%= content_tag :div, value, class: "alert alert-#{key}" %>
<% end %>
<%= yield %>
</div>
</body>
</html>
home.html.erb
<% if user_signed_in? %>
...
<% if current_user.profile %>
...
<% else %>
...
<% end %>
...
<% else %>
<div class="col-md-6">
<div class="well">
<h2 class="text-center">Trial Membership</h2>
<h4>Sign up for free and get trial access for a period of 10 days.</h4>
<br/>
<%= link_to "Sign up for Trial", new_user_registration_path(plan: #trial_plan), class: 'btn btn-primary btn-lg btn-block' %>
</div>
</div>
<div class="col-md-6">
<div class="well">
<h2 class="text-center">Pro Membership</h2>
<h4>Sign up for the pro account for €75/month and get access to all functions.</h4>
<%= link_to "Sign up for Pro", new_user_registration_path(plan: #pro_plan), class: 'btn btn-success btn-lg btn-block' %>
</div>
</div>
<% end %>
</div>
I fixed the problem, the thing you've mentioned about the database was right. The problem was that, for some reason, the db migration to Heroku was unsuccessful, without giving me any notice about it. After running:
Heroku run rails c
Plan.create(name: 'trial', price: 0)
Plan.create(name: 'pro', price: 75)
After running these commands the both plans were injected to the database of my Heroku app. My code seems to work perfectly fine now, altough I've changed the following piece of code according to your comment about hardcoding ID's
pages_controller.rb
class PagesController < ApplicationController
def home
if Plan.find_by name: 'trial'
#trial_plan = 1
end
if Plan.find_by name: 'pro'
#pro_plan = 2
end
end
end
Thanks for the heads up.

How to remove node below Post.all # static page

In my app when I am rendering Post.all in my static page home I am getting some code like this at the end of the page
[#<Post id: 3, title: "I loved you...", content: "how to short and place enter if the line is large ...", created_at: "2015-04-03 09:17:48", updated_at: "2015-04-03 10:34:47", image_file_name: "Penguins.jpg", image_content_type: "image/jpeg", image_file_size: 777835, image_updated_at: "2015-04-03 09:18:50">, #<Post id: 2, title: "I loved you...", content: "I loved you, and I probably still do,\r\nAnd for a w...", created_at: "2015-04-02 15:44:19", updated_at: "2015-04-02 15:44:19", image_file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil>, #<Post id: 1, title: "উত্তম ও অধম", content: "কুকুর আসিয়া এমন কামড়\r\nদিল পথিকের পায়\r\nকামড়ের চ...", created_at: "2015-04-02 15:41:51", updated_at: "2015-04-02 15:41:51", image_file_name: nil, image_content_type: nil, image_file_size: nil, image_updated_at: nil>]
how to remove that or stop getting that?
here is my gemfile
source 'https://rubygems.org'
gem 'rails', '4.2.1'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'therubyracer', platforms: :ruby
gem 'jquery-rails'
gem 'paperclip', '~> 4.2.1'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
group :development, :test do
gem 'sqlite3'
gem 'byebug'
gem 'web-console', '~> 2.0'
end
group :production do
gem 'pg'
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
In Pages controller home action I have put #post = Post.all
and in view I have put
<%= #post.each do |post|%>
<% if post.image.present?%>
<h1> <%= link_to post.title, post %></h1><br>
<%= image_tag post.image.url(:thumb)%>
<%= simple_format post.content %>
<hr color="blue" >
<% else %>
<h1> <%= link_to post.title, post %></h1><br>
<%= simple_format post.content %>
<hr color="blue">
<% end %>
<%end%>
you should remove the = in the first loop <%= #post.each do |post|%>
<% #post.each do |post|%>
<% if post.image.present?%>
<h1> <%= link_to post.title, post %></h1><br>
<%= image_tag post.image.url(:thumb)%>
<%= simple_format post.content %>
<hr color="blue" >
<% else %>
<h1> <%= link_to post.title, post %></h1><br>
<%= simple_format post.content %>
<hr color="blue">
<% end %>
<% end %>

Updating to 3.1.1 following RailsTutorial.org screencast

I am following the lesson 13 screencast from Railstutorial.org and am hung up on the error below:
Failures:
1) PagesController GET 'home' when signed in should have the right follower/following counts
Failure/Error: response.should have_selector('a', :href => following_user_path(#user),
expected following output to contain a <a href='/users/1/following'>0 following</a> tag:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Ruby on Rails Tutorial Sample App | Home</title>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]--><link href="/assets/blueprint/screen.css" media="screen" rel="stylesheet" type="text/css">
<link href="/assets/blueprint/print.css" media="print" rel="stylesheet" type="text/css">
<!--[if lt IE 8]><link href="/assets/blueprint/ie.css" media="screen" rel="stylesheet" type="text/css" /><![endif]--><link href="/assets/custom.css" media="screen" rel="stylesheet" type="text/css">
<script src="/assets/defaults.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
<header><img alt="Sample App" class="round" src="/assets/logo.png">
<nav class="round"><ul>
<li> Home
</li>
<li> Help
</li>
<li> Sign in
</li>
</ul></nav></header><section class="round"><h1>Home</h1>
<p>Find me in app/views/pages/home.html.erb</p>
Sign up now!
</section><footer><nav class="round"><ul>
<li> About </li>
<li> Contact </li>
<li> News </li>
<li> About </li>
</ul></nav></footer>
</div>
</body>
</html>
# ./spec/controllers/pages_controller_spec.rb:119:in `block (4 levels) in <top (required)>'
Finished in 7.32 seconds
10 examples, 1 failure
Failed examples:
rspec ./spec/controllers/pages_controller_spec.rb:117 # PagesController GET 'home' when signed in should have the right follower/following counts
my gemfile:
source 'http://rubygems.org'
gem 'rack' , '1.3.3'
gem 'rails', '3.1.1'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
gem 'gravatar_image_tag', '1.0.0.pre2'
# gem 'will_paginate', '3.0.pre2'
gem 'will_paginate', '~> 3.0.2'
gem 'sqlite3', '1.3.4'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'sass-rails', '~> 3.1.4'
gem 'coffee-rails', '~> 3.1.1'
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
group :development do
gem 'rspec-rails', '2.7.0'
# gem 'annotate-models', '1.0.4'
gem 'annotate', '2.4.0'
gem 'faker', '0.3.1'
end
group :test do
gem 'rspec-rails', '2.7.0'
gem 'webrat', '0.7.1'
gem 'spork', '0.9.0.rc8'
gem 'factory_girl_rails', '1.0'
# gem 'autotest', '4.4.6'
# gem 'autotest-rails-pure', '4.1.2'
# gem 'autotest-fsevent', '0.2.4'
# gem 'autotest-growl', '0.2.9'
end
Wondering possibly if its an rspec version problem? --
pages_controller_spec.rb
it "should have the right follower/following counts" do
get :home
response.should have_selector('a', :href => following_user_path(#user),
:content => "0 following")
response.should have_selector('a', :href => followers_user_path(#user),
:content => "1 follower")
end
pages_controller.rb
class PagesController < ApplicationController
def home
#title = "Home"
if signed_in?
#micropost = Micropost.new
#feed_items = current_user.feed.paginate(:page => params[:page])
end
end
def contact
#title = "Contact"
end
def about
#title = "About"
end
def help
#title = "Help"
end
end
when I comment out the pages_controller_spec.rb section I go green
Any thoughts?
Update 1:
Changing RSPEC versions did not work, tried 2.4.0, 2.6.1 and 2.6.4
Update 2:
Changing to Rails 3.1.0 did not work
Update 3:
Triple Checked running rspec in original sample app Rails 3.0.8 GREEN
update 4:
home page
<% if signed_in? %>
<table class="front" summary="For signed-in users">
<tr>
<td class="main">
<h1 class="micropost"> What's up? </h1>
<%= render 'shared/micropost_form' %>
<%= render 'shared/feed'%>
</td>
<td class="sidebar round">
<%= render 'shared/user_info' %>
<%= render 'shared/stats' %>
</td>
</tr>
</table>
<% else %>
<h1>Home</h1>
<p>Find me in app/views/pages/home.html.erb</p>
<%= link_to "Sign up now!", signup_path, :class => "signup_button round" %>
<% end %>
The error message suggests that when a user visits /pages/home they should see a link constructed from the following code:
<a href='/users/1/following'>0 following</a>
Do you actually see that link when you visit the home page?
If not, then you should add it, I'd imagine there's a section or chapter where the author walks you through doing that.

Resources