Fresh Nova install, yet cannot delete newly created Users - laravel-nova

This is a new Laravel Nova install. I added a few test users, but I am unable to delete any. After confirming that I wish to delete the Resource, nothing happens. Refresh shows nothing was deleted.
The Laravel Log is empty.
APP_ENV=local
APP_DEBUG=true
I have installed Vue Devtools and compiled npm to dev mode, so I am seeing the Vue Console errors.
I haven't added any code and am running the latest - Laravel Framework 5.8.29, Nova 2.0.9, PHP 7.3.7
Attempting to Delete User with ID 4.
Expected: Resource is deleted and no errors.
Actual: Devtools Vue Console shows:
DELETE https://nova.local/nova-api/users?search=&filters=W10%3D&trashed=&viaResource=&viaResourceId=&viaRelationship=&resources[]=4 405
vendor.js?id=09758f7de86ec728ec5f:6848 DELETE https://nova.local/nova-api/users?search=&filters=W10%3D&trashed=&viaResource=&viaResourceId=&viaRelationship=&resources[]=4 405
dispatchXhrRequest # vendor.js?id=09758f7de86ec728ec5f:6848
xhrAdapter # vendor.js?id=09758f7de86ec728ec5f:6699
dispatchRequest # vendor.js?id=09758f7de86ec728ec5f:7255
Promise.then (async)
request # vendor.js?id=09758f7de86ec728ec5f:7074
wrap # vendor.js?id=09758f7de86ec728ec5f:7495
request # app.js?id=a16899bd00909d3799c4:52998
deleteResources # vendor.js?id=09758f7de86ec728ec5f:32864
invokeWithErrorHandling # vendor.js?id=09758f7de86ec728ec5f:96710
invoker # vendor.js?id=09758f7de86ec728ec5f:97035
invokeWithErrorHandling # vendor.js?id=09758f7de86ec728ec5f:96710
Vue.$emit # vendor.js?id=09758f7de86ec728ec5f:98730
deleteResource # app.js?id=a16899bd00909d3799c4:9640
confirmDelete # app.js?id=a16899bd00909d3799c4:7397
invokeWithErrorHandling # vendor.js?id=09758f7de86ec728ec5f:96710
invoker # vendor.js?id=09758f7de86ec728ec5f:97035
invokeWithErrorHandling # vendor.js?id=09758f7de86ec728ec5f:96710
Vue.$emit # vendor.js?id=09758f7de86ec728ec5f:98730
handleConfirm # app.js?id=a16899bd00909d3799c4:9064
submit # app.js?id=a16899bd00909d3799c4:39744
invokeWithErrorHandling # vendor.js?id=09758f7de86ec728ec5f:96710
invoker # vendor.js?id=09758f7de86ec728ec5f:97035
original._wrapper # vendor.js?id=09758f7de86ec728ec5f:102388
vendor.js?id=09758f7de86ec728ec5f:95481
[Vue warn]: Error in v-on handler (Promise/async): "Error: Request failed with status code 405"
found in
---> <ResourceTable> at resources/js/components/ResourceTable.vue
<LoadingView> at resources/js/components/LoadingView.vue
<Card> at resources/js/components/Card.vue
<LoadingView> at resources/js/components/LoadingView.vue
<ResourceIndex> at resources/js/views/Index.vue
<Root>
warn # vendor.js?id=09758f7de86ec728ec5f:95481
logError # vendor.js?id=09758f7de86ec728ec5f:96740
globalHandleError # vendor.js?id=09758f7de86ec728ec5f:96735
handleError # vendor.js?id=09758f7de86ec728ec5f:96695
(anonymous) # vendor.js?id=09758f7de86ec728ec5f:96712
Promise.catch (async)
invokeWithErrorHandling # vendor.js?id=09758f7de86ec728ec5f:96712
invoker # vendor.js?id=09758f7de86ec728ec5f:97035
invokeWithErrorHandling # vendor.js?id=09758f7de86ec728ec5f:96710
Vue.$emit # vendor.js?id=09758f7de86ec728ec5f:98730
deleteResource # app.js?id=a16899bd00909d3799c4:9640
confirmDelete # app.js?id=a16899bd00909d3799c4:7397
invokeWithErrorHandling # vendor.js?id=09758f7de86ec728ec5f:96710
invoker # vendor.js?id=09758f7de86ec728ec5f:97035
invokeWithErrorHandling # vendor.js?id=09758f7de86ec728ec5f:96710
Vue.$emit # vendor.js?id=09758f7de86ec728ec5f:98730
handleConfirm # app.js?id=a16899bd00909d3799c4:9064
submit # app.js?id=a16899bd00909d3799c4:39744
invokeWithErrorHandling # vendor.js?id=09758f7de86ec728ec5f:96710
invoker # vendor.js?id=09758f7de86ec728ec5f:97035
original._wrapper # vendor.js?id=09758f7de86ec728ec5f:102388
vendor.js?id=09758f7de86ec728ec5f:96744 Error: Request failed with status code 405
at createError (vendor.js?id=09758f7de86ec728ec5f:7186)
at settle (vendor.js?id=09758f7de86ec728ec5f:7337)
at XMLHttpRequest.handleLoad (vendor.js?id=09758f7de86ec728ec5f:6747)
logError # vendor.js?id=09758f7de86ec728ec5f:96744
globalHandleError # vendor.js?id=09758f7de86ec728ec5f:96735
handleError # vendor.js?id=09758f7de86ec728ec5f:96695
(anonymous) # vendor.js?id=09758f7de86ec728ec5f:96712
Promise.catch (async)
invokeWithErrorHandling # vendor.js?id=09758f7de86ec728ec5f:96712
invoker # vendor.js?id=09758f7de86ec728ec5f:97035
invokeWithErrorHandling # vendor.js?id=09758f7de86ec728ec5f:96710
Vue.$emit # vendor.js?id=09758f7de86ec728ec5f:98730
deleteResource # app.js?id=a16899bd00909d3799c4:9640
confirmDelete # app.js?id=a16899bd00909d3799c4:7397
invokeWithErrorHandling # vendor.js?id=09758f7de86ec728ec5f:96710
invoker # vendor.js?id=09758f7de86ec728ec5f:97035
invokeWithErrorHandling # vendor.js?id=09758f7de86ec728ec5f:96710
Vue.$emit # vendor.js?id=09758f7de86ec728ec5f:98730
handleConfirm # app.js?id=a16899bd00909d3799c4:9064
submit # app.js?id=a16899bd00909d3799c4:39744
invokeWithErrorHandling # vendor.js?id=09758f7de86ec728ec5f:96710
invoker # vendor.js?id=09758f7de86ec728ec5f:97035
original._wrapper # vendor.js?id=09758f7de86ec728ec5f:102388

I believe I have found my own solution.
IIS does not handle all Verbs by default, specifically, PUT and DELETE are not handled by default. I added DELETE to the Allowed verbs and - deletion!

Related

Spree test rspec Failure/Error: expecting <"new"> but rendering with <[]>

I've been trying to pass this test suite on our spree app but it keeps saying:
Failure/Error: expect(response).to render_template(:new)
expecting <"new"> but rendering with <[]>
Here's the test:
context 'New action' do
it 'render view new template' do
spree_get :new
expect(response).to render_template(:new)
end
end
What's weird is when I test this code it passes, they're basically the same:
context 'Index action' do
it 'render view index template' do
spree_get :index
expect(response).to render_template(:index)
end
it 'index should have a status code of 200', focus: true do
spree_get :index
expect(response.status).to eq(200)
end
end
also tried adding render_views doesn't work. I also followed the instruction on this link spree_test still no luck. I also run it many times without touching the code hoping that it will work nothing happens.
Additional Information
spec/support/spree_controller_request.rb
require 'spree/testing_support/controller_requests'
RSpec.configure do |config|
config.include Spree::TestingSupport::ControllerRequests, :type => :controller
config.include Devise::TestHelpers, :type => :controller
end
spec/spec_helper.rb
# This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
ENV['RAILS_ENV'] = 'test'
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
require 'capybara/rspec'
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
# config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
# config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
# if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
# config.default_formatter = "doc"
# end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
# config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
end
end
spec/rails_helper.rb
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
require 'capybara/rails'
# require 'capybara/rspec'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }
# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove these lines.
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
puts e.to_s.strip
exit 1
end
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# FactoryBot
config.include FactoryBot::Syntax::Methods
# Database Cleaner
# source: http://www.virtuouscode.com/2012/08/31/configuring-database_cleaner-with-rails-rspec-capybara-and-selenium/
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = false
config.before(:suite) do
# RAILS_ENV and Rails.env can be different at times; fail if any of the two is different
abort("The Rails environment is not running in test mode!") if !Rails.env.test? || ENV['RAILS_ENV'] != 'test'
# Prevent database truncation if the environment is not test
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.strategy = :transaction
end
config.before(:each, js: true) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
# when testing methods with transactions, we have to manage commits / rollbacks manually (ex: option_type_generator_spec.rb):
# 1. Add testing_transactions: true to the example call
# - this tells database_cleaner to NOT wrap the example in a transaction (we'll manage the test and cleanup ourselves)
# 2. Wrap the test logic inside a transaction
# - make sure that the transaction to be tested allows for nested transactions (requires_new: true)
# 3. Execute the test sequence and the necessary tests
# 4. Afterwards, ensure cleanup:
# - rollback the test transaction
# - after rollback, inspect the data to make sure that test details did not persist
config.around(:each, :testing_transactions => true) do |ex|
DatabaseCleaner.strategy = nil
ex.run
DatabaseCleaner.strategy = :truncation
end
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# 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!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
end
# Shoulda
require 'shoulda/matchers'
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end

Error in cancancan ability initializer when testing controllers

I added cancancan gem to my app, but it broked all my controller and feature tests. The error start in ability.rb initialize: the user variable is nil.
Here is the error log of one of the tests:
14) TestCasesController DELETE #destroy when not logged-in redirects to sign-in page
Failure/Error: if user.teacher?
NoMethodError:
undefined method `teacher?' for nil:NilClass
# ./app/models/ability.rb:5:in `initialize'
# /usr/local/rvm/gems/ruby-2.3.1/gems/cancancan-1.15.0/lib/cancan/controller_additions.rb:361:in `new'
# /usr/local/rvm/gems/ruby-2.3.1/gems/cancancan-1.15.0/lib/cancan/controller_additions.rb:361:in `current_ability'
# /usr/local/rvm/gems/ruby-2.3.1/gems/cancancan-1.15.0/lib/cancan/controller_additions.rb:342:in `authorize!'
# /usr/local/rvm/gems/ruby-2.3.1/gems/cancancan-1.15.0/lib/cancan/controller_resource.rb:49:in `authorize_resource'
# /usr/local/rvm/gems/ruby-2.3.1/gems/cancancan-1.15.0/lib/cancan/controller_resource.rb:34:in `load_and_authorize_resource'
# /usr/local/rvm/gems/ruby-2.3.1/gems/cancancan-1.15.0/lib/cancan/controller_resource.rb:10:in `block in add_before_action'
# /usr/local/rvm/gems/ruby-2.3.1/gems/rails-controller-testing-1.0.1/lib/rails/controller/testing/template_assertions.rb:61:in `process'
# /usr/local/rvm/gems/ruby-2.3.1/gems/devise-4.2.0/lib/devise/test/controller_helpers.rb:33:in `block in process'
# /usr/local/rvm/gems/ruby-2.3.1/gems/devise-4.2.0/lib/devise/test/controller_helpers.rb:100:in `catch'
# /usr/local/rvm/gems/ruby-2.3.1/gems/devise-4.2.0/lib/devise/test/controller_helpers.rb:100:in `_catch_warden'
# /usr/local/rvm/gems/ruby-2.3.1/gems/devise-4.2.0/lib/devise/test/controller_helpers.rb:33:in `process'
# /usr/local/rvm/gems/ruby-2.3.1/gems/rails-controller-testing-1.0.1/lib/rails/controller/testing/integration.rb:12:in `block (2 levels) in <module:Integration>'
# ./spec/controllers/test_cases_controller_spec.rb:182:in `block (3 levels) in <top (required)>'
# ./spec/controllers/test_cases_controller_spec.rb:193:in `block (4 levels) in <top (required)>'
Here is the corresponding action:
describe "DELETE #destroy" do
let!(:test_case) { create(:test_case) }
subject { delete :destroy, params: { id: test_case } }
context "when not logged-in" do
before { subject }
it "redirects to sign-in page" do
expect(response).to redirect_to(new_user_session_url)
end
end
end
This is my controller:
class TestCasesController < ApplicationController
include ApplicationHelper
load_and_authorize_resource
before_action :authenticate_user!
before_action :find_test_case, only: [:show, :edit, :update, :destroy, :test]
before_action :find_question, only: [:index, :new, :create, :test_all]
def index
#test_cases = TestCase.where(question: #question)
end
def new
#test_case = TestCase.new
end
def create
#test_case = #question.test_cases.build(test_case_params)
if #test_case.save
flash[:success] = "Caso de teste criado!"
redirect_to #test_case
else
render 'new'
end
end
def show
end
def edit
end
def update
if #test_case.update_attributes(test_case_params)
flash[:success] = "Caso de teste atualizado!"
redirect_to #test_case
else
render 'edit'
end
end
def destroy
question = #test_case.question
#test_case.destroy
flash[:success] = "Caso de teste deletado!"
redirect_to question_test_cases_url(question)
end
def test
result = #test_case.test(plain_current_datetime, "pas", params[:source_code])
#output = result[:output]
#results = [ { title: #test_case.title, status: result[:status] } ]
respond_to { |format| format.js }
end
def test_all
#results = #question.test_all(plain_current_datetime, "pas", params[:source_code])
respond_to { |format| format.js }
end
private
def test_case_params
params.require(:test_case).permit(:title, :description, :input, :output, :question_id)
end
def find_test_case
#test_case = TestCase.find(params[:id])
end
def find_question
#question = Question.find(params[:question_id])
end
end
This is my ability class:
class Ability
include CanCan::Ability
def initialize(user)
if user.teacher?
can :manage, [Exercise, Question, TestCase]
can :manage, Team, owner: user
can [:read, :create], Team
can [:enroll], Team do |team|
!team.enrolled?(user)
end
can [:unenroll], Team do |team|
team.enrolled?(user)
end
end
end
end
This is my rails_helper (from rspec):
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
require 'support/helpers/relationships'
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Checks for pending migration and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# 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!
# Helpers
config.include Helpers::Relationships, type: :model
config.include Devise::Test::ControllerHelpers, :type => :controller
config.include Warden::Test::Helpers
end
Any tips of how to fix that?
OBS: I'm using Devise for authentication, it provides me the required current_user to cancancan work.
The primary reason you're getting a nil:NilClass error is because current_user is nil unless you are signed in via Devise. Your ability needs to handle for when a user is not logged in, something like this:
def initialize(user)
return unless user.present?
if user.teacher?
...
end
end
If you return nil from your ability, the authorization fails and is handled accordingly.

Capybara holds only one authorized request, all others return 401

My problem is that capybara holds only one authorized request (doesn't matter was it authorization through the login form or through the helper login_as method)
Other (second, third) requests are unauthorized!
It doesn't mater what driver I use. Where the problem can be?
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort('The Rails environment is running in production mode!') if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'
require 'capybara/rspec'
require 'capybara/poltergeist'
# NOTE: For Chrome support
Capybara.register_driver :selenium do |app|
Capybara::Selenium::Driver.new(app, :browser => :chrome)
end
# Capybara.register_driver(:poltergeist) { |app| Capybara::Poltergeist::Driver.new(app, js_errors: false) }
# Capybara.javascript_driver = :poltergeist
Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Checks for pending migration and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
config.include WaitForAjax
config.include FeatureHelpers
config.include Devise::TestHelpers, type: :controller
config.include Warden::Test::Helpers
config.extend ControllerHelpers, type: :controller
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = false
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# 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!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
config.before :suite do
Warden.test_mode!
end
end
Most probably between the first request and the second, rspec cleans up the DB.
For this second request the user form the first request no more exists. You should create another user and login/authorize it.
Ex:
For each it block you'll have to do a login_as(a_new_just_created_user). Yes, you can put this into a before block to be executed for the entire test suite.
describe '' do
before do
login_as(a_new_just_created_user)
end
context '' do
it '' { get 'api/url' } # first user logged in
it '' { get 'api/url' } # second user logged in
end
context '' do
it '' { get 'api/url' } # third user logged in
end
end

Functional Test Keeps Failing (Rspec, Devise)

I'm trying to implement an rspec functional test to check that a user is signed in with devise. I've looked through my code again and again and tried different solutions but so far nothing has worked.
I've included what I believe are the relevant files. Let me know if anything is missing. Any recommendations are appreciated.
spec/rails_helper.rb
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
# Add additional requires below this line. Rails is not loaded until this point!
require 'spec_helper'
require 'rspec/rails'
# note: require 'devise' after require 'rspec/rails'
require 'devise'
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
# Checks for pending migration and applies them before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# 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!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
#Added for Devise
config.include Devise::Test::ControllerHelpers, :type => :controller
end
spec/controllers/users_controller_spec.rb
require 'rails_helper'
describe UsersController, :type => :controller do
before do
#user = User.create!(email: 'example#example.com', password: 'example')
end
# let(:user) { User.create!(email: 'example#example.com', password: 'example') }
describe 'GET #show' do
context "when user is logged in" do
before do
sign_in #user
end
it "loads correct user details" do
get :show, id: #user.id
expect(response).to have_http_status(200)
expect(assigns(:user)).to eq #user
end
end
context "when no user is logged in" do
it "redirects to login" do
get :show, id: #user.id
expect(response).to redirect_to(root_path)
end
end
end
end
And my feedback from the terminal after running bundle exec rpsec
Failures:
1) UsersController GET #show when user is logged in loads correct user details
Failure/Error: elsif user?
NoMethodError:
undefined method `user?' for #<Ability:0x007fa1d784cb98>
# ./app/models/ability.rb:9:in `initialize'
# /Users/Admin/.rvm/gems/ruby-2.3.0/gems/cancancan-1.15.0/lib/cancan/controller_additions.rb:361:in `new'
# /Users/Admin/.rvm/gems/ruby-2.3.0/gems/cancancan-1.15.0/lib/cancan/controller_additions.rb:361:in `current_ability'
# /Users/Admin/.rvm/gems/ruby-2.3.0/gems/cancancan-1.15.0/lib/cancan/controller_additions.rb:342:in `authorize!'
# /Users/Admin/.rvm/gems/ruby-2.3.0/gems/cancancan-1.15.0/lib/cancan/controller_resource.rb:49:in `authorize_resource'
# /Users/Admin/.rvm/gems/ruby-2.3.0/gems/cancancan-1.15.0/lib/cancan/controller_resource.rb:34:in `load_and_authorize_resource'
# /Users/Admin/.rvm/gems/ruby-2.3.0/gems/cancancan-1.15.0/lib/cancan/controller_resource.rb:10:in `block in add_before_action'
# /Users/Admin/.rvm/gems/ruby-2.3.0/gems/rails-controller-testing-1.0.1/lib/rails/controller/testing/template_assertions.rb:61:in `process'
# /Users/Admin/.rvm/gems/ruby-2.3.0/gems/devise-4.2.0/lib/devise/test/controller_helpers.rb:33:in `block in process'
# /Users/Admin/.rvm/gems/ruby-2.3.0/gems/devise-4.2.0/lib/devise/test/controller_helpers.rb:100:in `catch'
# /Users/Admin/.rvm/gems/ruby-2.3.0/gems/devise-4.2.0/lib/devise/test/controller_helpers.rb:100:in `_catch_warden'
# /Users/Admin/.rvm/gems/ruby-2.3.0/gems/devise-4.2.0/lib/devise/test/controller_helpers.rb:33:in `process'
# /Users/Admin/.rvm/gems/ruby-2.3.0/gems/rails-controller-testing-1.0.1/lib/rails/controller/testing/integration.rb:12:in `block (2 levels) in <module:Integration>'
# ./spec/controllers/users_controller_spec.rb:19:in `block (4 levels) in <top (required)>'
2) UsersController GET #show when no user is logged in redirects to login
Failure/Error: expect(response).to redirect_to(root_path)
Expected response to be a redirect to <http://test.host/> but was a redirect to <http://test.host/users/sign_in>.
Expected "http://test.host/" to be === "http://test.host/users/sign_in".
# ./spec/controllers/users_controller_spec.rb:29:in `block (4 levels) in <top (required)>'
Finished in 0.90214 seconds (files took 11.05 seconds to load)
6 examples, 2 failures
Failed examples:
rspec ./spec/controllers/users_controller_spec.rb:18 # UsersController GET #show when user is logged in loads correct user details
rspec ./spec/controllers/users_controller_spec.rb:27 # UsersController GET #show when no user is logged in redirects to login
A friend actually helped me figure it out. Apparently there's some issue that involves the seperate gem cancancan. I had to go into the models/ability.rb file and change a line in it.
In the original code the line if !user.admin? was just user?
So if you run into this same issue, that's the fix!
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new #guest user (not logged in)
# can :manage, User, id: user.id
if user.admin?
can :manage, :all
elsif !user.admin?
can :manage, User, id: user.id
else
can :read, :all
end
end
end

Doorkeeper error help needed

I am using doorkeeper for OAuth functionality on my ruby on rails application. Also I am using devise for user security management.
Here is my current doorkeeper.rb file:
Doorkeeper.configure do
orm :active_record
resource_owner_authenticator do
user_signed_in? || redirect_to(new_user_session_url)
end
admin_authenticator do
user_signed_in? || redirect_to(new_user_session_url)
end
enable_application_owner :confirmation => true
# authorization_code_expires_in 10.minutes
# access_token_expires_in 2.hours
# use_refresh_token
# default_scopes :public
# optional_scopes :write, :update
# client_credentials :from_basic, :from_params
# access_token_methods :from_bearer_authorization, :from_access_token_param, :from_bearer_param
# test_redirect_uri 'urn:ietf:wg:oauth:2.0:oob'
# skip_authorization do |resource_owner, client|
# client.superapp? or resource_owner.admin?
# end
# realm "Doorkeeper"
end
When I access /oauth/applications, I get an error page which says "uninitialized constant Admin", and "config/initializers/doorkeeper.rb:18:in `block (2 levels) in '".
What am I doing wrong?
I have resolved the issue. The problem lay in rails server caching the doorkeeper.rb initialiser file and I needed to restart the server after I had edited that file.

Resources