Ruby test doesn't Increment User count - ruby-on-rails

I'm new to Ruby and I'm trying to create a test that will create a new user. I'm using devise and my test_helper.rb looks like:
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
# Add more helper methods to be used by all tests here...
end
class ActionController::TestCase
include Devise::TestHelpers
def sign_in_user
#request.env["devise.mapping"] = Devise.mappings[:user]
sign_in users(:user1)
end
end
My User Fixture looks like:
user1:
id: 1
email: user1#test.com
encrypted_password: abcdef1
role: Sales
created_at: <%= Time.now %>
My Test is very simple:
require 'test_helper'
class UsersControllerTest < ActionController::TestCase
setup do
#controller = UsersController.new
sign_in_user
end
test "should create user" do
assert_difference('User.count') do
post :create, user: {name: "Test", password: "Troll", password_confirmation: "Troll", email: "test#test.com", role: "Sales"}
end
assert_redirected_to user_path(assigns(:user))
end
end
But whenever I run rake test, I always get the error that User.count didn't increase by 1 (expected 2 but was 1). What am I doing wrong? Any help would be greatly appreciated!

Related

Rails 6 Devise test helpers without RSpec

Devise test helpers with Rails 6 without Rspec doesn't seem to work. Here is the code, any idea why it might be getting errors?
Controller:
class VehiclesController < ApplicationController
before_action :authenticate_user!, only: [:new]
def index
#vehicles = Vehicle.all
end
def new
#vehicle = Vehicle.new
end
end
test/test_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require_relative "../config/environment"
require "rails/test_help"
class ActiveSupport::TestCase
# Run tests in parallel with specified workers
parallelize(workers: :number_of_processors)
# Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.
fixtures :all
include Devise::Test::IntegrationHelpers
end
user fixture:
valid_user:
first_name: "Toseef"
last_name: "zafar"
email: "exampleuser#gmail.com"
encrypted_password: <%= Devise::Encryptor.digest(User, '12345678') %>
controller test:
require "test_helper"
class VehiclesControllerTest < ActionDispatch::IntegrationTest
test "should be able to get to new form page" do
sign_in users(:valid_user)
get new_vehicles_url
assert_response :success
end
end
and this is the error I get:
Failure:
VehiclesControllerTest#test_should_be_able_to_get_to_new_form_page [/test/controllers/vehicles_controller_test.rb:12]:
Expected response to be a <2XX: success>, but was a <302: Found> redirect to <http://www.example.com/users/sign_in>
Response body: <html><body>You are being redirected.</body></html>
rails test test/controllers/vehicles_controller_test.rb:9
Also, I don't know why it would point to http://www.example.com
The devise user model has got confirmable hence when we do sign_in users(:valid_user) devise creates a user but because the user is not confirmed (i.e. no confirmation email link clicking is involved) when we go to a secured URL it takes us back to login because user hasn't confirmed through clicking on the link from the email.
The solution to this is to set confirmed_at value to Time.now before sign_in
e.g.
#user = users(:valid_user)
#user.confirmed_at = Time.now
sign_in #user
after doing that the tests passed! :)

Rails: Shoulda matcher, Minitest and Devise query

Rails 5.1.6
Ruby 2.5.0
I am trying to run a simple test for a redirect in one of my controllers using Shoulda Matcher gem (following the documentation) and minitest:
home_controller.rb:
class HomeController < ApplicationController
def index
#redirect on login
if user_signed_in?
redirect_to controller: 'home', action: "dashboard_#{current_user.user_role}"
end
end
test/controllers/home_controller_test.rb:
class HomeControllerTest < ActionController::TestCase
context 'GET #index' do
setup { get :index }
should redirect_to(action: "dashboard_#{current_user.user_role}")
end
end
Error:
Undefined method current_user for homecontrollertest
I'm using Devise and was wondering if anyone could assist to get my test to work? I can provide more info if required.
EDIT:
Tried this:
home_controller_test.rb
require 'test_helper'
class HomeControllerTest < ActionController::TestCase
include Devise::Test::ControllerHelpers
context 'GET #index' do
user = users(:one)
sign_in user
get :index
should redirect_to(action: "dashboard_#{user.user_role}")
end
end
users.yml
one:
name: 'John'
email: 'some#user.com'
encrypted_password: <%= Devise::Encryptor.digest(User, 'password') %>
user_role: 1
Gemfile
gem 'shoulda', '~> 3.5'
gem 'shoulda-matchers', '~> 2.0'
Test_helper.rb
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
# Add more helper methods to be used by all tests here...
end
Get undefined method users error.
NoMethodError: undefined method `users' for HomeControllerTest:Class
/mnt/c/code/studytaps/test/controllers/home_controller_test.rb:9:in `block in <class:HomeControllerTest>'
/mnt/c/code/studytaps/test/controllers/home_controller_test.rb:8:in `<class:HomeControllerTest>'
/mnt/c/code/studytaps/test/controllers/home_controller_test.rb:4:in `<top (required)>'
Tasks: TOP => test
(See full trace by running task with --trace)
You need to include devise test helper to your test
class HomeControllerTest < ActionController::TestCase
include Devise::Test::ControllerHelpers
context 'GET #index' do
user = users(:one) # if you use fixtures
user = create :user # if you use FactoryBot
sign_in user
get :index
should redirect_to(action: "dashboard_#{user.user_role}")
end
end

Using Devise in rspec feature tests

I've written the following rspec feature test spec:
require "rails_helper"
RSpec.describe "Team management", type: :feature do
user_sign_in
describe "User creates a new team" do
...
expect(page).to have_link("#{team_name}")
end
end
The user_sign_in method is defined in my rails_helper.rb:
ENV['RAILS_ENV'] ||= 'test'
require 'spec_helper'
require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
require 'capybara/rails'
...
module UserSignInHelpers
def user_sign_in
before(:each) do
#request.env['devise.mapping'] = Devise.mappings[:user]
#current_user = FactoryGirl.create(:user)
#current_user.confirm
sign_in :user, #current_user
end
end
end
RSpec.configure do |config|
...
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
config.extend UserSignInHelpers, type: :controller
config.extend UserSignInHelpers, type: :feature
config.include Devise::TestHelpers, type: :controller
config.include Devise::TestHelpers, type: :feature
end
The user_sign_in method works from all of my controller specs but when I run my feature spec it fails with:
Team management
User creates a new team
example at ./spec/features/user_creates_a_new_team_spec.rb:19 (FAILED - 1)
Failures:
1) Team management User creates a new team
Failure/Error: Unable to find matching line from backtrace
NoMethodError:
undefined method `env' for nil:NilClass
# /Users/xxxx/.rvm/gems/ruby-2.2.1/gems/devise-3.5.1/lib/devise/test_helpers.rb:24:in `setup_controller_for_warden'
I don't understand why this works in controller tests and not feature tests. Is there something I can do make this work in feature tests?
There is a basic problem with what you are trying to do. (Devise work on top of Warden)Warden is a
Rack middleware, but RSpec controller specs don't even include Rack,
as these types of specs are not meant to run your full application
stack, but only your controller code.
Ref
Test with Capybara
I have a simple support helper, that allows me to login and logout users:
module Auth
def create_user!
#user = User.create(email: 'foo#bar.com', password: '11111111')
end
def sign_in_user!
setup_devise_mapping!
sign_in #user
end
def sign_out_user!
setup_devise_mapping!
sign_out #user
end
def setup_devise_mapping!
#request.env["devise.mapping"] = Devise.mappings[:user]
end
def login_with_warden!
login_as(#user, scope: :user)
end
def logout_with_warden!
logout(:user)
end
def login_and_logout_with_devise
sign_in_user!
yield
sign_out_user!
end
def login_and_logout_with_warden
Warden.test_mode!
login_with_warden!
yield
logout_with_warden!
Warden.test_reset!
end
end
in a feature:
RSpec.describe "Team management", type: :feature do
describe "User creates a new team" do
login_and_logout_with_warden do
# tests goes here
end
end
end
in a controller:
RSpec.describe "Team management", type: :controller do
describe "User creates a new team" do
login_and_logout_with_devise do
# tests goes here
end
end
end

How to sign_in for Devise to Test Controller with Minitest

I'm newbie to Rails Testing.
After following some tutorial online, I could able to setup and run testing for Model.
But when trying to test for Controller, Testing was failed as it is redirected to login page.
I've tried every instruction I can find on web to sign in for devise and still couldn't able to sign in and move forward.
Appreciate if someone could help and give me a direction to move forward.
AwardedBidsControllerTest
test_should_get_index FAIL (0.45s)
MiniTest::Assertion: Expected response to be a <:success>, but was <302>
Below is my setup
test/test_helper.rb
ENV["RAILS_ENV"] = "test"
require File.expand_path("../../config/environment", __FILE__)
require "rails/test_help"
require "minitest/rails"
require "minitest/reporters"
Minitest::Reporters.use!(
Minitest::Reporters::SpecReporter.new,
ENV,
Minitest.backtrace_filter
)
class ActiveSupport::TestCase
fixtures :all
include FactoryGirl::Syntax::Methods
end
class ActionController::TestCase
include Devise::TestHelpers
end
test/controllers/awarded_bids_controller_test.rb
require "test_helper"
class AwardedBidsControllerTest < ActionController::TestCase
test "should get index" do
user = create(:user)
sign_in user
get :index
assert_response :success
end
end
app/controllers/awarded_bids_controller.rb
class AwardedBidsController < ApplicationController
before_filter :authenticate_user!
def index
#awarded_bids = AwardedBid.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #awarded_bids }
end
end
end
test/factories/users.rb
#using :login instead of :email.
FactoryGirl.define do
factory :user do |u|
u.login "user"
u.name "Normal"
u.surname "User"
u.password "Abc2011"
end
end
Below is the version info.,
JRuby 1.7.21(Ruby 1.9.3)
Rails 3.2.22
Devise 3.0.4
Minitest 4.7.5
From integration_helpers.rb, for example:
class PostsTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
test 'authenticated users can see posts' do
sign_in users(:bob)
get '/posts'
assert_response :success
end
end
In your test_helper.rb file's ActiveSupport::TestCase class, add a new method log_in_as like this:
require "test_helper"
ENV["RAILS_ENV"] = "test"
require File.expand_path("../../config/environment", __FILE__)
require "rails/test_help"
require "minitest/rails"
require "minitest/reporters"
Minitest::Reporters.use!(
Minitest::Reporters::SpecReporter.new,
ENV,
Minitest.backtrace_filter
)
class ActiveSupport::TestCase
fixtures :all
include FactoryGirl::Syntax::Methods
# 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.id
end
end
private
# Returns true inside an integration test.
def integration_test?
defined?(post_via_redirect)
end
end
class ActionController::TestCase
include Devise::TestHelpers
end
Then, use this log_in_as method instead of sign_in in your test:
require "test_helper"
class AwardedBidsControllerTest < ActionController::TestCase
test "should get index" do
user = create(:user)
log_in_as user
get :index
assert_response :success
end
end

make a helper for my methods for integration testing in rails 3

I'm preparing some integration tests on my rails 3.2.16 application, I figured that, in my user scenarios, I have several calls that I repeat over many tests, so I would like to DRY them up, by placing them in a separate common module,
for example I have created /test/integration/my_test_helpers.rb:
require 'test_helper'
module MyTestHelper
def login_user(email, password, stay = 0)
login_data = {
email: email,
password: password,
remember_me: stay
}
post "/users/sign_in", user: login_data
assert_redirected_to :user_root
end
end
and tried to use it in my integration test:
require 'test_helper'
require "./my_test_helpers.rb"
class CreateCommentTest < ActionDispatch::IntegrationTest
setup do
#user = users(:user1)
end
test "create comment" do
login_user #user.email, "password", 1
end
end
I get exception:
`require': cannot load such file -- ./my_test_helpers.rb (LoadError)
How can I load the module? is it right to make MyTestHelpers a module?
You should put your helper in support folder(test/support/my_test_helpers.rb, or something) and load module in test_helper.rb:
ENV["RAILS_ENV"] ||= "test"
require File.expand_path("../../config/environment", __FILE__)
require "rails/test_help"
require_relative "./support/my_test_helpers"
require "minitest/rails"
class ActiveSupport::TestCase
ActiveRecord::Migration.check_pending!
fixtures :all
# Add more helper methods to be used by all tests here...
end
Do not remember include your module:
require 'test_helper'
class CreateCommentTest < ActionDispatch::IntegrationTest
include MyTestHelper
setup do
#user = users(:user1)
end
test "create comment" do
login_user #user.email, "password", 1
end
end

Resources