controller spec failing with ActionController::RoutingError with get method - ruby-on-rails

I am building a Rails 3 application, and I am a little confused with a controller spec. here what I have in the application:
routes.rb
get "/:user_name/library", :to => 'users#library', :as => :user_library
users_controller.rb
class UsersController < ApplicationController
def library
end
end
users_controller_spec.rb
describe "UsersController" do
describe "#library" do
let(:user){FactoryGirl.create(:user)}
it "renders the users/library.html.erb view" do
get :library, :parameters => {:user_name => user.user_name}
end
end
end
this example dose not run and it shows the following error
Failure/Error: get :library,:parameters => {:user_name => user.user_name}
ActionController::RoutingError:
No route matches {:parameters=>{:user_name=>"UserName"}, :controller=>"users", :action=>"library"}

Get rid of the :parameters key in your get:
get :library, :user_name => user.user_name

Related

Rspec no route matches, checking for flash message in controller

I need to test that a flash message comes up when a specific exception is raised. I am getting a no route matches error and have looked through the other topics with "Rspec Controller test, No Routes matches" and am still not sure what is wrong. This is my first time writing an rspec test. Commented out lines are various other attempts to get test to pass.
audit/businesses_controller.rb:
class Audit::BusinessesController < ApplicationController
# PUT /audit/businesses/:id
def update
remove_deleted_account_numbers_in(params)
#business = #jurisdiction.businesses.find(params[:id])
#business.changed_by = current_user
if #business.update_attributes(audit_business_params)
success_message('update')
else
#business.initialize_accounts
#business = #business
render :edit, alert: t('flash.save_failed')
end
rescue ActiveRecord::StatementInvalid => e
if e.message.include? "foreign key constraint"
#business = #jurisdiction.businesses.find(params[:id])
#business.initialize_accounts
#business = #business
render :edit, alert: "This account number is in use and cannot be deleted"
else
raise e
end
end
business_controller_spec.rb:
require "spec_helper"
describe Audit::BusinessesController do
describe "handling ActiveRecord::StatementInvalid" do
before {delete, url = 'audit/jurisdictions/:jurisdiction_id/businesses/:id(.:format)'}
it "should rescue with a flash message" do
# /audit/jurisdictions/:jurisdiction_id/businesses/:id(.:format)
# delete, businesses_id: '80776', jurisdiction_id: '795', format: 'html', id: "234769"
expect(page).to have_content("This account number is in use and cannot be deleted")
end
end
end
rake routes:
audit_businesses GET
/audit/jurisdictions/:jurisdiction_id/businesses(.:format)
audit/businesses#
POST /audit/jurisdictions/:jurisdiction_id/businesses(.:format)
audit/businesses#create
new_audit_business GET
/audit/jurisdictions/:jurisdiction_id/businesses/new(.:format)
audit/businesses#new
edit_audit_business GET
/audit/jurisdictions/:jurisdiction_id/businesses/:id/edit(.:format)
audit/businesses#edit
audit_business
GET /audit/jurisdictions/:jurisdiction_id/businesses/:id(.:format)
audit/businesses#show
PUT /audit/jurisdictions/:jurisdiction_id/businesses/:id(.:format) audit/businesses#update
DELETE /audit/jurisdictions/:jurisdiction_id/businesses/:id(.:format) audit/businesses#destroy
Error Message:
Failure/Error: before { delete audit_business_path(:jurisdiction_id, :id, :format) }
ActionController::RoutingError:
No route matches {:controller=>"audit/businesses", :action=>"/audit/jurisdictions/jurisdiction_id/businesses/id.format"}
# ./spec/controllers/businesses_controller_spec.rb:6:in `block (3 levels) in <top (required)>'
When I change the spec to:
describe Audit::BusinessesController do
describe "handling ActiveRecord::StatementInvalid" do
it "should rescue with a flash message" do
put :update, :jurisdiction_id => 1, :id => 1, :format => html
expect(controller).to set_flash[:alert].to(/This account number is in use and cannot be deleted/).now
The error is:
Failure/Error: put :update, :jurisdiction_id => 1, :id => 1, :format => html
NoMethodError:
undefined method `can_update?' for nil:NilClass
routes.rb:
namespace :audit do
root to: 'site#home'
resources :labels, only: ['index', 'destroy'] do
post 'delete_queue', on: :collection
get 'print', on: :collection
get 'print_view', on: :collection
get 'mark_printed', on: :collection
get 'users', on: :collection
end
resources :auditor_goals
resources :contracts
resource :contract_work, only: %w[show update], controller: 'contract_work'
resources :manpower
resource :county_budgets, only: :update do
get 'search'
end
get 'intro_letter_search' => 'files#intro_letter_search'
put 'intro_letter_update' => 'files#intro_letter_update'
get 'search' => 'files#search'
get 'calendar' => 'files#calendar'
get 'autocomplete' => 'files#autocomplete'
get 'direct' => 'files#direct'
get 'size_code_select' => 'businesses#size_code_select'
scope '/jurisdictions/:jurisdiction_id' do
resources :businesses, controller: 'businesses'
resources :files, controller: 'files' do
get 'print', on: :member
end
# get 'page/:page', action: :index, on: :collection
end
end
for rspec test instead write
expect(page).to have_content("flash message")
where "flash message" is the actual message of the error or exception you're trying to make pass. Eg for, flash[:notice] = "An error occurred", you would put have_content("An error occurred")
Hope that helps?!
Justin
#TzokinB - I believe "Capybara::ElementNotFound: Unable to find xpath "/html" typically means the test set is now looking for a view. Have you associated a view for to action in your controller?

No Route Matches ... Rails Engine

So I keep getting the error:
No route matches {:action=>"create", :controller=>"xaaron/api_keys"}
Which is thrown in the test:
it "should not create an api key for those not logged in" do
post :create
expect(response).to redirect_to xaaron.login_path
end
when I go to spec/dummy and run the rake routes command I see:
api_keys GET /api_keys(.:format) xaaron/api_keys#index
POST /api_keys(.:format) xaaron/api_keys#create
new_api_key GET /api_keys/new(.:format) xaaron/api_keys#new
edit_api_key GET /api_keys/:id/edit(.:format) xaaron/api_keys#edit
api_key GET /api_keys/:id(.:format) xaaron/api_keys#show
PATCH /api_keys/:id(.:format) xaaron/api_keys#update
PUT /api_keys/:id(.:format) xaaron/api_keys#update
DELETE /api_keys/:id(.:format) xaaron/api_keys#destroy
Which shows that yes this route does exist. My routes file for this engine looks like:
Xaaron::Engine.routes.draw do
get 'login' => 'sessions#new', :as => 'login'
get 'logout' => 'sessions#destroy', :as => 'logout'
get 'signup' => 'users#new', :as => 'signup'
get 'permission_denied' => 'error#denied', :as => 'permission_denied'
get 'record_not_found' => 'error#error', :as => 'record_not_found'
get 'password_reset' => 'password_resets#edit', :as => 'rest_user_password'
resource :error, controller: 'error'
resources :users
resources :api_keys
resources :sessions
resources :roles
resources :password_resets
end
What am I missing?
update
For those of you curious how I am getting these routes, its because the dummy app's routes file is set up (by default) as such:
Rails.application.routes.draw do
mount Xaaron::Engine => "/xaaron"
end
Update II
I have been reading this api docs on how routing is done in engines and I believe the way I have done this is correct, how ever the controller is defined as such:
module Xaaron
class ApiKeysController < ActionController::Base
before_action :authenticate_user!
def index
#api_key = Xaaron::ApiKey.where(:user_id => current_user.id)
end
def create
#api_key = Xaaron::ApiKey.new(:user_id => current_user.id, :api_key => SecureRandom.hex(16))
create_api_key(#api_key)
end
def destroy
Xaaron::ApiKey.find(params[:id]).destroy
flash[:notice] = 'Api Key has been deleted.'
redirect_to xarron.api_keys_path
end
end
end
You need to tell your spec you are using the engine routes:
describe ApiKeysController do
routes { Xaaron::Engine.routes }
it "should not create an api key for those not logged in" do
post :create
expect(response).to redirect_to xaaron.login_path
end
end

Rspec Controller Test No Route Matches Error

Rspec is not recognising my controller routes. I am using Versionist gem to version my API and I am using a path version (so /v1/ to version my API as shown below.).
constraints :subdomain => "api" do
api_version(:module => "V1", :path => {:value => "v1"}, :defaults => {:format => :json}, :default => true) do
match '/orders' => 'orders#index', :via => :get
The route in rake routes is shown as:
GET /v1/orders(.:format) V1/orders#index {:subdomain=>"api", :format=>:json}
My controller is located in app/controller/v1/orders_controller.rb.
For the rspec test, I have a orders_controller_spec.rb, I have:
require 'spec_helper'
module V1
describe OrdersController do
describe "GET #index" do
it "throws an error on incorrect params" do
get :index
end
end
end
end
The error I get is:
1) V1::OrdersApiController GET #index throws an error on incorrect param
Failure/Error: get :index
ActionController::RoutingError:
No route matches {:controller=>"v1/orders"}
What is wrong here? How come no route matches v1/orders? In rake routes, I see the route right there as shown above: GET /v1/orders(.:format) V1/orders#index {:subdomain=>"api", :format=>:json}. It says GET /v1/orders. Where is the problem here?

Rspec "No route matches" error

I am attempting to test my sessions_controller in Rails 3 app with rspec, but keep coming across this error when I run rspec on my sessions_controller_spec.rb:
ActionController::RoutingError:
No route matches {:controller=>"sessions", :action=>"create"}
Here are all the relevant files:
routes.rb
match 'event' => 'event#create', via: [:post]
match 'event/agenda' => 'event#agenda', via: [:get]
match 'testLogin' => 'application#test_login', via: [:get]
post 'session' => 'session#create'
sessions_controller.rb
class SessionsController < ApplicationController
def create
#MY CODE HERE
end
end
sessions_controller_spec.rb
require 'spec_helper'
describe SessionsController, :type => :controller do
describe "POST #create" do
context "invalid params" do
it "returns a response with status failed if all required parameters are not passed in" do
post "create"
response.body.status.should eq("failed")
end
end
end
end
If there's any other info I can provide to help let me know. Thanks a lot!
post 'session' => 'session#create'
Your route definition is looking for a SessionController, but you have defined a SessionsController. Fix your route.
post 'session' => 'sessions#create'

Rspec and non-RestFul routes

I am doing homework but I have problem with non-RestFul routes.
My spec is:
require 'spec_helper'
describe MoviesController do
describe 'searching TMDb' do
before :each do
#fake_results = [mock('Movie'), mock('Movie')]
end
it 'should call the model method that performs TMDb search' do
Movie.should_receive(:find_in_tmdb).with('Star Wars').
and_return(#fake_results)
get :search_similar_movies, { :search_terms => 'Star Wars' }
end
end
end
In config/routes.rb I have:
resources :movies
'movies/search_similar_movies/:search_terms'
But when I run autotest it gives me error that begins with:
/usr/local/lib/ruby/gems/1.9.1/gems/actionpack-3.1.0/lib/action_dispatch/routing/mapper.rb:181:in `default_controller_and_action': missing :action (ArgumentError)
It's obvious that something is wrong is config/routes.rb. How to solve this?
Your route should be something like
resources :movies do
get 'search_similar_movies', :on => :collection
end
or
match 'movies/search_similar_movies/:search_terms' => 'movies#search_similar_movies', :via => :get

Resources