Initially, I had code that had DEPRECATION WARNINGS:
Ruby on Rails: Deprecation Warnings
I've changed this code to some extent, but I still have one warning left.
See the warning and code as below.
How to fix it and make sure all the tests pass? Thanks in advance.
DEPRECATION WARNING: Using positional arguments in integration tests has been deprecated, ETA: 00:00:30
in favor of keyword arguments, and will be removed in Rails 5.1.
Deprecated style:
get "/profile", { id: 1 }, { "X-Extra-Header" => "123" }
New keyword style:
get "/profile", params: { id: 1 }, headers: { "X-Extra-Header" => "123" }
(called from block (2 levels) in at /home/ubuntu/workspace/origin/test/integration/following_test.rb:30)
68/68: [=========================================================] 100% Time: 00:00:04, Time: 00:00:04
Finished in 4.25284s
68 tests, 336 assertions, 0 failures, 0 errors, 0 skips
require 'test_helper'
class FollowingTest < ActionDispatch::IntegrationTest
def setup
#user = users(:michael)
#other = users(:archer)
log_in_as(#user)
end
test "following page" do
get following_user_path(#user)
assert_not #user.following.empty?
assert_match #user.following.count.to_s, response.body
#user.following.each do |user|
assert_select "a[href=?]", user_path(user)
end
end
test "followers page" do
get followers_user_path(#user)
assert_not #user.followers.empty?
assert_match #user.followers.count.to_s, response.body
#user.followers.each do |user|
assert_select "a[href=?]", user_path(user)
end
end
test "should follow a user the standard way" do
assert_difference '#user.following.count', 1 do
post relationships_path, followed_id: #other.id
end
end
test "should follow a user with Ajax" do
assert_difference '#user.following.count', 1 do
post relationships_path(followed_id: #other.id), xhr: true
end
end
test "should unfollow a user the standard way" do
#user.follow(#other)
relationship = #user.active_relationships.find_by(followed_id: #other.id)
assert_difference '#user.following.count', -1 do
delete relationship_path(relationship)
end
end
test "should unfollow a user with Ajax" do
#user.follow(#other)
relationship = #user.active_relationships.find_by(followed_id: #other.id)
assert_difference '#user.following.count', -1 do
delete relationship_path(relationship), xhr: true
end
end
end
Try this and Go Green... :D
require 'test_helper'
class FollowingTest < ActionDispatch::IntegrationTest
def setup
#user = users(:michael)
#other = users(:archer)
log_in_as(#user)
end
test "following page" do
get following_user_path(#user)
assert_not #user.following.empty?
assert_match #user.following.count.to_s, response.body
#user.following.each do |user|
assert_select "a[href=?]", user_path(user)
end
end
test "followers page" do
get followers_user_path(#user)
assert_not #user.followers.empty?
assert_match #user.followers.count.to_s, response.body
#user.followers.each do |user|
assert_select "a[href=?]", user_path(user)
end
end
test "should follow a user the standard way" do
assert_difference '#user.following.count', 1 do
post relationships_path, params: { followed_id: #other.id }
end
end
test "should follow a user with Ajax" do
assert_difference '#user.following.count', 1 do
post relationships_path, params: { followed_id: #other.id }, xhr: true
end
end
test "should unfollow a user the standard way" do
#user.follow(#other)
relationship = #user.active_relationships.find_by(followed_id: #other.id)
assert_difference '#user.following.count', -1 do
delete relationship_path(relationship)
end
end
test "should unfollow a user with Ajax" do
#user.follow(#other)
relationship = #user.active_relationships.find_by(followed_id: #other.id)
assert_difference '#user.following.count', -1 do
delete relationship_path(relationship), xhr: true
end
end
end
Related
I'm using devise + rspec + factory + shoulda and having trouble with my controller specs. I've read a bunch of articles and docs but couldn't figure out what the best way is to log_in the user and use that user instance.
Task is nested under user so index route is /users/:user_id/tasks and task belongs_to :assigner, class_name: "User" and belongs_to :executor, class_name: "User"
At the moment with following code both tests fail. What is the best approach for properly sign_in the user and use it in the controller tests?
The error message for the first one:
Failure/Error: expect(assigns(:tasks)).to eq([assigned_task, executed_task])
expected: [#<Task id: 1, assigner_id: 1, executor_id: 2, .....>, #<Task id: 2, assigner_id: 3, executor_id: 1, ......>]
got: nil
(compared using ==)
The error for the second one:
Failure/Error: it { is_expected.to respond_with :ok }
Expected response to be a 200, but was 302
tasks_controller_spec.rb
require "rails_helper"
describe TasksController do
describe "when user is signed in" do
describe "collections" do
login_user
let(:assigned_task) { create(:task, assigner: #user) }
let(:executed_task) { create(:task, executor: #user) }
let(:other_task) { create(:task) }
context "GET index" do
before do
get :index, user_id: #user.id
end
it "assigns user's tasks" do
expect(assigns(:tasks)).to eq([assigned_task, executed_task])
end
it { is_expected.to respond_with :ok }
end
context "GET incoming_tasks"
end
end
end
controller_macros.rb
module ControllerMacros
def login_user
before(:each) do
#request.env["devise.mapping"] = Devise.mappings[:user]
#user = create(:user)
sign_in #user
end
end
end
tasks controller
def index
#tasks = Task.alltasks(current_user).uncompleted.includes(:executor, :assigner).order("deadline DESC").paginate(page: params[:page], per_page: Task.pagination_per_page)
end
Add following line in rails_helper.
config.include ControllerMacros, :type => :controller
SEE this thread.
I am assuming this only fails in rspec. When you test in browser it works fine.
Working through the Rails Tutorial and in chapter 8 I can't get one of my tests to pass. Been checking around for hours... any help would be greatly appreciated.
ERROR["test_login_with_valid_information", UsersLoginTest, 2015-09-07 00:25:37 -0700]
test_login_with_valid_information#UsersLoginTest (1441610737.31s)
BCrypt::Errors::InvalidHash:
BCrypt::Errors::InvalidHash: invalid hash
app/controllers/sessions_controller.rb:8:in `create'
test/integration/users_login_test.rb:22:in `block in <class:UsersLoginTest>'
app/controllers/sessions_controller.rb:8:in `create'
test/integration/users_login_test.rb:22:in `block in <class:UsersLoginTest>'
22/22: [============] 100% Time: 00:00:00, Time: 00:00:00
Finished in 0.46288s
22 tests, 44 assertions, 0 failures, 1 errors, 0 skips
users_login_test.rb
require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
#user = users(:michael)
end
test "login with invalid information" do
get login_path
assert_template 'sessions/new'
post login_path, session: { email: "", password: "" }
assert_template 'sessions/new'
assert_not flash.empty?
get root_path
assert flash.empty?
end
test "login with valid information" do
get login_path
post login_path, session: { email: #user.email, password: 'password' }
assert_redirected_to #user
follow_redirect!
assert_template 'users/show'
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(#user)
end
end
sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by(email: params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in user
redirect_to user
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
end
end
I know it's been a while since originally posted, but I had exactly the same error and my problem was a typo (missing =) in
users.yml
michael:
name: Michael Example
email: michael#example.com
password_digest: <% User.digest('password') %>
where it should have been
michael:
name: Michael Example
email: michael#example.com
password_digest: <%= User.digest('password') %>
#PraveenGeorge is correct - you need to back track and review your code at least since the last time the tests passed. Based on the fact that the content of the two files you've shared match to the tutorial, the problem lies elsewhere (and, unfortunately, out of sight from us on SO).
Perhaps it's in user.rb where you def User.digest(string) or in sessions_helper.rb?
Dear #Travislogan : As the ruby on rails tutorial itself is self explanatory in most possible way, you might have missed some of the steps/code before you reached into the section 8.2. So please cross check all tests and your project code from at least the previous chapter to the current one , one more time.It will help you to find out the error in your code.
I tried fixing it but to no avail. I'm pretty sure I followed the tutorial. This happened in chapter 8 of The Rails Tutorial.
Here is the error when i run bundle exec rake test
ERROR["test_current_user_returns_nil_when_remember_digest_is_wrong", SessionsHelperTest, 2015-09-17 16:33:02 +0100]
test_current_user_returns_nil_when_remember_digest_is_wrong#SessionsHelperTest (1442503982.53s)
NoMethodError: NoMethodError: undefined method `user' for #<SessionsHelperTest:0xbdef3ba8>
test/helpers/sessions_helper_test.rb:6:in `setup'
test/helpers/sessions_helper_test.rb:6:in `setup'
ERROR["test_current_user_returns_right_user_when_session_is_nil", SessionsHelperTest, 2015-09-17 16:33:02 +0100]
test_current_user_returns_right_user_when_session_is_nil#SessionsHelperTest (1442503982.55s)
NoMethodError: NoMethodError: undefined method `user' for #<SessionsHelperTest:0xb9575274>
test/helpers/sessions_helper_test.rb:6:in `setup'
test/helpers/sessions_helper_test.rb:6:in `setup'
ERROR["test_login_with_remembering", UsersLoginTest, 2015-09-17 16:33:02 +0100]
test_login_with_remembering#UsersLoginTest (1442503982.61s)
NoMethodError: NoMethodError: undefined method `session' for nil:NilClass
test/test_helper.rb:27:in `log_in_as'
test/integration/users_login_test.rb:51:in `block in <class:UsersLoginTest>'
test/test_helper.rb:27:in `log_in_as'
test/integration/users_login_test.rb:51:in `block in <class:UsersLoginTest>'
ERROR["test_login_without_remembering", UsersLoginTest, 2015-09-17 16:33:02 +0100]
test_login_without_remembering#UsersLoginTest (1442503982.73s)
NoMethodError: NoMethodError: undefined method `session' for nil:NilClass
test/test_helper.rb:27:in `log_in_as'
test/integration/users_login_test.rb:56:in `block in <class:UsersLoginTest>'
test/test_helper.rb:27:in `log_in_as'
test/integration/users_login_test.rb:56:in `block in <class:UsersLoginTest>'
28/28: [=======================================================================================================] 100% Time: 00:00:03, Time: 00:00:03
Finished in 3.29948s
28 tests, 62 assertions, 0 failures, 4 errors, 0 skips
test/test_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require "minitest/reporters"
Minitest::Reporters.use!
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
# Add more helper methods to be used by all tests here...
# Returns true if a test user is logged in.
def is_logged_in?
!session[:user_id].nil?
end
# Logs in a test user.
def log_in_as(user, options = {})
password = options[:password] || 'password'
remember_me = options[:remember_me] || '1'
if integration_test?
post login_path, session: { email: user.email,
password: password,
remember_me: remember_me }
else
session[:user_id] = user.user_id # this is line 27
end
end
private
# Returns true inside an integration test.
def integration_test?
defined?(post_via_reditect)
end
end
test/helpers/sessions_helper.rb
require 'test_helper'
class SessionsHelperTest < ActionView::TestCase
def setup
#user = user(:microte) # Line 6
remember(#user)
end
test "current_user returns right user when session is nil" do
assert_equal #user, current_user
assert is_logged_in?
end
test "current_user returns nil when remember digest is wrong" do
#user.update_attribute(:remember_digest, User.digest(User.new_token))
assert_nil current_user
end
end
test/integration/users_login_test.rb
require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
#user = users(:microte)
end
test "login with invalid information" do
get login_path
assert_template 'sessions/new'
post login_path session: { email: "", password: "" }
assert_template 'sessions/new'
assert_not flash.empty?
get root_path
assert flash.empty?
end
test "login with valid information" do
get login_path
post login_path, session: { email: #user.email, password: 'password' }
assert_redirected_to #user
follow_redirect!
assert_template 'users/show'
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(#user)
end
test "login with valid information follwed by logout" do
get login_path
post login_path, session: { email: #user.email, password: 'password' }
assert is_logged_in?
assert_redirected_to #user
follow_redirect!
assert_template 'users/show'
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(#user)
delete logout_path
assert_not is_logged_in?
assert_redirected_to root_url
# Simulate a user clicking logout in a second window
delete logout_path
follow_redirect!
assert_select "a[href=?]", login_path
assert_select "a[href=?]", logout_path, count: 0
assert_select "a[href=?]", user_path(#user), count: 0
end
test "login with remembering" do
log_in_as(#user, remember_me: '1') # Line 51
assert_not_nil cookies['remember_token']
end
test "login without remembering" do
log_in_as(#user, remember_me: '0') # Line 56
assert_nil cookies['remember_token']
end
end
Thanks for your help.
It looks like the first two errors are in your session_helper: your setup defines #user = user(:microte).
Not sure about the errors in the remembering tests are; the tests you've shared appear to be fine. I suggest you compare the code changes against what's in the tutorial to see what the cause of these errors are.
Seems like you are getting an error when trying to pull out a user from your fixtures. Check your fixtures/users.yml file and see if you have a microte user defined. It should look something like this(just an example):
microte:
name: "Test User"
email: "test_user#example.com"
password_digest: <%= User.digest("password")%>
slug: <%= "Test User".parameterize %>
activated: true
In the tutorial the user provided is named :michael
As others before me have noted, you wrote :microte instead.
Check in your users.yml fixture how you named him there, and make sure they match.
As a bit of explanation: in the beginning of your test there is a setup method that prepares your test setting:
def setup
#user = users(:microte)
end
the user you are instantiating here, is put into the fixtures file.
FAIL["test_test_login_with_valid_information", UsersLoginTest, 2015-08-27 20:00:02 +0000]
test_test_login_with_valid_information#UsersLoginTest (1440705602.54s)
Expected at least 1 element matching "a[href="/users.762146111"]", found 0..
Expected 0 to be >= 1.
test/integration/users_login_test.rb:18:in `block in '
2/2:
[=======================================================================================================] 100% Time: 00:00:00, Time: 00:00:00
Finished in 0.46825s 2 tests, 10 assertions, 1 failures, 0 errors, 0
skips
Here's user_login_test.rb
require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
#user = users(:michael)
end
test "test login with valid information" do
get login_path
post login_path, session: {email: #user.email, password: "password"}
assert_redirected_to #user
follow_redirect!
assert_template "users/show"
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", users_path(#user)
end
test "login with invalid information" do
get login_path
assert_template 'sessions/new'
post login_path, session: { email: "", password: "" }
assert_template 'sessions/new'
assert flash.any?
get root_path
assert flash.empty?
end
end
User.yml
michael:
name: michael
email: michael#example.com
password_digest: <%= User.digest("password") %>
I'd double-check your header template and confirm that the appropriate code is there for the "Profile" link (listing 8.16) as that appears what's failing the test.
I'm not super savvy with Rails, but this part of the error has me a little concerned: matching "a[href="/users.762146111"]". I'd expect that to be /users/762….
I've been stuck on this one for a while and keep getting 2 errors when I rake test. Referencing Listing 9.23 testing point. Any help would be much appreciated.
Test Error:
1) Error:
UsersControllerTest#test_should_redirect_update_when_logged_in_as_wrong_user:
NameError: undefined local variable or method `user_id' for #<UsersControllerTest:0x007fbff6be3120>
test/test_helper.rb:24:in `log_in_as'
test/controllers/users_controller_test.rb:35:in `block in <class:UsersControllerTest>'
2) Error:
UsersControllerTest#test_should_redirect_edit_when_logged_in_as_wrong_user:
NameError: undefined local variable or method `user_id' for #<UsersControllerTest:0x007fbff6c01850>
test/test_helper.rb:24:in `log_in_as'
test/controllers/users_controller_test.rb:28:in `block in <class:UsersControllerTest>'
29 runs, 66 assertions, 0 failures, 2 errors, 0 skips
User_Controller_Test file:
require 'test_helper'
class UsersControllerTest < ActionController::TestCase
def setup
#user = users(:michael)
#other_user = users(:archer)
end
test "should get new" do
get :new
assert_response :success
end
test "should redirect edit when not logged in" do
get :edit, id: #user
assert_not flash.empty?
assert_redirected_to login_url
end
test "should redirect update when not logged in" do
patch :update, id: #user, user: { name: #user.name, email: #user.email }
assert_not flash.empty?
assert_redirected_to login_url
end
test "should redirect edit when logged in as wrong user" do
log_in_as(#other_user)
get :edit, id: #user
assert flash.empty?
assert_redirected_to root_url
end
Test_Helper.rb:
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
class ActiveSupport::TestCase
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
def is_logged_in?
!session[:user_id].nil?
end
#logs in a test user
def log_in_as(user, options = {})
password = options[:password] || 'password'
remember_me = options[:remember_me] || '1'
if integration_test?
post login_path, session: { email: user.email,
password: password,
remember_me: remember_me}
else
session[:user_id] = user_id
end
end
private
#returns true inside an int. test
def integration_test?
defined?(post_via_redirect)
end
end
And where does user_id come from here?
def log_in_as(user, options = {})
...
if integration_test?
...
else
session[:user_id] = user_id
end
end
Seems it should be:
session[:user_id] = user.id