rails rake test, url helpers not working - ruby-on-rails

Getting the following when running my capybara rails tests with "rake test". Problem seems to be url helpers I'm using in my application.html.erb:
DashboardLoginTest#test_login_and_check_dashboard:
ActionView::Template::Error: arguments passed to url_for can't be handled. Please require routes or provide your own implementation
app/views/layouts/application.html.erb:29:in `_app_views_layouts_application_html_erb__938277815294620636_4045700'
test/integration/dashboard_login_test.rb:6:in `block in <class:DashboardLoginTest>'
Here's line 29 in application.html.erb that its complaining about:
<%= link_to("asdf", root_path, {:class => 'brand'}) %>
Here's what the test looks like:
test "login and check dashboard" do
visit("/")
assert page.has_content?("welcome")
end
Here's my test_helper.rb:
ENV["RAILS_ENV"] ||= "test"
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'
require 'factory_girl'
require 'capybara/rails'
include Warden::Test::Helpers
Warden.test_mode!
def main_app
Rails.application.class.routes.url_helpers
end
class ActiveSupport::TestCase
ActiveRecord::Migration.check_pending!
fixtures :all
end
class ActionDispatch::IntegrationTest
# Make the Capybara DSL available in all integration tests
include Capybara::DSL
include Rails.application.routes.url_helpers
def sign_in(user = nil)
if user.nil?
user = FactoryGirl.create(:user)
$current_user = user
end
login_as(user, :scope => :user)
user.confirmed_at = Time.now
user.save
end
end

Related

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

minitest-rails - test:helpers - NameError: Unable to resolve controller for ApplicationHelper

I have strange error when i run my tests for helpers with rake test:helpers
ApplicationHelper::dummy#test_0001_must return string:
NameError: Unable to resolve controller for ApplicationHelper::dummy
Test:
require "test_helper"
describe ApplicationHelper do
include ApplicationHelper
context "dummy" do
it "must return string" do
result = dummy()
result.must_be_kind_of ( String )
result.wont_be_empty
end
end
end
My helper
module ApplicationHelper
def dummy
"hello world".html_safe
end
end
My test_helper
ENV["RAILS_ENV"] = "test"
require File.expand_path("../../config/environment", __FILE__)
require "rails/test_help"
require "minitest/rails"
require "minitest/rails/capybara"
require 'minitest/rg'
require "warden_mock"
class ActiveSupport::TestCase
fixtures :all
class << self
alias :context :describe
end
end
class ActionController::TestCase
def setup
request.env['warden'] = WardenMock.new # mockup warden
User.current = request.env['warden'].user
end
register_spec_type(/.*/, self)
end
rails 4.1.6
minitest-rails 2.1.0
Try to comment out require "minitest/rails/capybara" in your test_helper.rb and require it only in your feature tests

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

Setting up one time login with minitest/capybara for running rails tests

I'm using capybara with minitest on Rails 2.3.14. Like most applications, this one also requires login to do anything inside the site. I'd like to be able to login once per test-suite and use that session throughout all tests that are run. How do I refactor that to the minitest_helper? Right now my helper looks something like this:
#!/usr/bin/env ruby
ENV['RAILS_ENV'] = 'test'
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
gem 'minitest'
gem 'capybara_minitest_spec'
require 'minitest/unit'
require 'minitest/spec'
require 'minitest/mock'
require 'minitest/autorun'
require 'capybara/rails'
require 'factory_girl'
FactoryGirl.find_definitions
class MiniTest::Spec
include FactoryGirl::Syntax::Methods
include Capybara::DSL
include ActionController::URLWriter
before(:each) do
# .. misc global setup stuff, db cleanup, etc.
end
after(:each) do
# .. more misc stuff
end
end
thanks.
Here’s an example of multiple sessions and custom DSL in an integration test
require 'test_helper'
class UserFlowsTest < ActionDispatch::IntegrationTest
fixtures :users
test "login and browse site" do
# User avs logs in
avs = login(:avs)
# User guest logs in
guest = login(:guest)
# Both are now available in different sessions
assert_equal 'Welcome avs!', avs.flash[:notice]
assert_equal 'Welcome guest!', guest.flash[:notice]
# User avs can browse site
avs.browses_site
# User guest can browse site as well
guest.browses_site
# Continue with other assertions
end
private
module CustomDsl
def browses_site
get "/products/all"
assert_response :success
assert assigns(:products)
end
end
def login(user)
open_session do |sess|
sess.extend(CustomDsl)
u = users(user)
sess.https!
sess.post "/login", :username => u.username, :password => u.password
assert_equal '/welcome', path
sess.https!(false)
end
end
end
Source : http://guides.rubyonrails.org/testing.html#helpers-available-for-integration-tests

Resources