assert_routing with method is giving an error instead of failing - ruby-on-rails-3

In my rails 3.2.3 app, I have a topics controller, which is modeled as a resource. I want to write a functional test to verify that post on /topics is a valid route. This should fail first, and then I will add the code to fix it. However, I am getting an error in the routing test, instead of a failure. What am I doing wrong?(Note: If I fix the route in routes.rb, the test passes - just not sure why I am getting an error instead of a failure in the test):
# topics_controller_test.rb
test 'route exists to create topic' do
assert_routing({:path => '/topics', :method => 'post'} , { :controller => "topics", :action => "create"}, {}, {}, 'could not route to create topic')
end
# routes.rb
resources :topics, :only => [:new]
# terminal output
$ rake test:functionals
Run options:
# Running tests:
.....E.
Finished tests in 0.373543s, 18.7395 tests/s, 53.5414 assertions/s.
1) Error:
test_route_exists_to_create_topic(TopicsControllerTest):
ActionController::RoutingError: No route matches "/topics"
.../gems/ruby-1.9.3-p0/gems/actionpack-3.2.3/lib/action_dispatch/routing/route_set.rb:633:in `recognize_path'
.../gems/ruby-1.9.3-p0/gems/actionpack-3.2.3/lib/action_dispatch/testing/assertions/routing.rb:210:in `recognized_request_for'
.../gems/ruby-1.9.3-p0/gems/actionpack-3.2.3/lib/action_dispatch/testing/assertions/routing.rb:42:in `assert_recognizes'
.../gems/ruby-1.9.3-p0/gems/actionpack-3.2.3/lib/action_dispatch/testing/assertions/routing.rb:118:in `assert_routing'
`.../myapp/test/functional/topics_controller_test.rb:25:in block in <class:TopicsControllerTest>'`
>> 7 tests, 20 assertions, 0 failures, 1 errors, 0 skips

The created route in routes.rb is different from the route your testing. If you want to route to the :create action in the controller, in your routes.rb you should use:
resources :topics, :only => [:create]
See the routing topic in the RailsGuides.

Related

Rails 3 functional tests: Can't mass-assign protected attributes: controller, action

When running functional tests on my controller code in a Rails 3 project, I have a fatal error; the params variable contains controller and action, and ActiveModel is not happy about it:
ActiveModel::MassAssignmentSecurity::Error: Can't mass-assign protected attributes: controller, action
/Users/phooze/.rvm/gems/ruby-1.9.3-p0/gems/activemodel-3.2.1/lib/active_model/mass_assignment_security/sanitizer.rb:48:in `process_removed_attributes'
/Users/phooze/.rvm/gems/ruby-1.9.3-p0/gems/activemodel-3.2.1/lib/active_model/mass_assignment_security/sanitizer.rb:20:in `debug_protected_attribute_removal'
/Users/phooze/.rvm/gems/ruby-1.9.3-p0/gems/activemodel-3.2.1/lib/active_model/mass_assignment_security/sanitizer.rb:12:in `sanitize'
/Users/phooze/.rvm/gems/ruby-1.9.3-p0/gems/activemodel-3.2.1/lib/active_model/mass_assignment_security.rb:228:in `sanitize_for_mass_assignment'
/Users/phooze/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.1/lib/active_record/attribute_assignment.rb:75:in `assign_attributes'
/Users/phooze/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.1/lib/active_record/base.rb:495:in `initialize'
/Users/phooze/Documents/rails-app/app/controllers/credentials_controller.rb:40:in `new'
The application call is to the "new" method (where the error is occurring), the code is:
# Credential#create (POST)
def create
#credential = Credential.new(params)
# ... controller continues
end
Finally, my test case:
test "should create credential" do
assert_difference('Credential.count', 1) do
post :create, { :fid => "foobarbaz", :credentials_hash => "f00ba7f00ba7", :uid => "10023", :cid => "342" }
end
assert_response :created
end
Changing my controller code to a "separate" parameter hash containing ONLY the fid, credentials_hash, uid, and cid makes it work. I'm pretty sure Rails is trying to be "nice" and provide me with addtional values for testing, but it seems to be causing problems.
Any recommendations on how to solve this?
Looks like you have set config.active_record.mass_assignment_sanitizer = :strict
in your test environment only, but not in development or production, because params always contains controller and action, in any environment.
I think the best-practice recommendation here is to always use form_for, so that you'd have your credentials in params[:credential], or, indeed, do params.slice(:fid, :uid, etc).

No request params in constraint when testing route

When I run this in practice it works, but I can't seem to write a working test for my route constraint with rspec.
When the test runs the constraint is triggered, but the request params are empty, thus it does not validate and the test fails.
I am running Rails 3.0.9, rspec-rails 2.6.1 and rspec 2.6.0.
config/routes.rb
match ":param1-unique-:param2" => "controller#index",
:constraints => ParamConstraint.new
lib/param_constraint.rb
class ParamConstraint
def matches?(request)
#request ||= request
valid_param1? && valid_param2?
end
def valid_param1?
#request.params[:param1] == "lorem"
end
def valid_param2?
#request.params[:param2] == "ipsum"
end
end
spec/routing/param_constraint_spec.rb
require 'spec_helper'
describe "param constraint routing" do
it "recognizes route for param1 and param2" do
{ :get => "/lorem-unique-ipsum" }.
should route_to(
:controller => "controller",
:action => "index",
:param1 => "lorem",
:param2 => "ipsum"
)
end
end
Update
If I inspect the request in the constraint I get the following output:
#<ActionDispatch::Request:0x007fee140ff910 #env={
"rack.version"=>[1, 1],
"rack.input"=>#<StringIO:0x007fee1446da48>,
"rack.errors"=>#<StringIO:0x007fee1446e768>,
"rack.multithread"=>true,
"rack.multiprocess"=>true,
"rack.run_once"=>false,
"REQUEST_METHOD"=>"GET",
"SERVER_NAME"=>"example.org",
"SERVER_PORT"=>"80",
"QUERY_STRING"=>"",
"PATH_INFO"=>"/lorem-unique-ipsum",
"rack.url_scheme"=>"http",
"HTTPS"=>"off",
"SCRIPT_NAME"=>"",
"CONTENT_LENGTH"=>"0"
}>
I ran into this same issue today, searching for an answer brought me to this page's question. For what it's worth, I had to resort to writing a request spec instead.
context "passing params that satisfy ParamConstraint" do
before do
visit "/lorem-unique-ipsum"
end
it "should serve up a page with content" do
# replace this with some assertion that gets satisfied by
# pages served up when ParamConstraint.new.matches? returns true
page.should have_selector("html body div#foo")
page.should_not have_selector("html body div#bar")
end
end
context "passing params that DO NOT satisfy ParamConstraint" do
before do
visit "/other-unique-other"
end
it "should serve up a page with different content" do
# replace this with some assertion that gets satisfied by
# pages served up when ParamConstraint.new.matches? returns false
page.should_not have_selector("html body div#foo")
page.should have_selector("html body div#bar")
end
end
This doesn't answer your question, which I take to be "how to test routing constraint", as the proper way would be via a routing spec. But given this gap in how request.params works when you use "should route_to", this is a workaround. A request spec, as opposed to a routing spec, will fill request.params correctly.
Same issue exists years later, with rspec-core 3.4.4, rspec-rails 3.4.2, rails 4.2.6. Don't have time to dig into exactly why...
You can use a request spec as suggested above, but don't use it to test the page contents. Instead, replicate a routing test (route_to) by checking the conversion of URL paths to request params:
RSpec.describe 'routes', type: :request do
describe '/:slug' do
it 'routes correctly' do
get '/test-product-slug'
expect(request.params).to eq(
'controller' => 'product',
'action' => :index,
'slug' => 'test-product-slug'
)
end
end
end

How Do You Expire A Memcached Entry On Heroku

I am using action caching on my Rails 3 app on Heroku with the :expires_in option. I've tried calling expire_action, directly in the controller upon update, and within a sweeper. Nothing seems to expire the cache entry properly.
In my controller:
caches_action :embed, :if => Proc.new { |c| c.request.format.js? || c.request.format.rss? }, :expires_in => 5.minutes
In my action:
expire_action :action => :embed, :format => :js
And I've also attempted it in a sweeper, attempting to use the url generator to get the exact key:
expire_action obj_embed_url(#obj.unique_token)
I wonder if it is Heroku using the Varnish cache layer, which you can't expire. (The cache clearly expires after the 5 minutes, because I can see the content update.) It appears that I have the memcached add-on configured correctly (using the Dalli gem; config.cache_store = :dalli_store), and I can see the appropriate environment variables...
$ heroku config |grep MEM
MEMCACHE_PASSWORD => xxxxxxxxxxxxxxxxx
MEMCACHE_SERVERS => xxx.xxx.northscale.net
MEMCACHE_USERNAME => appxxxxxx%40heroku.com
What am I missing here?
finally figured this out.
Heroku's paths must not be matching up with the expire create/expire calls. so if you specify the path in the cache creation, and call that path specifically in the expire, it will work. also i had to use "expire_fragment" instead of "expire_action". here's my code:
in your controller:
caches_action :load, :up, :juice, :fresh, :cache_path => :custom_cache_path.to_proc
def custom_cache_path
path = "#{params[:controller]}/#{params[:action]}"
path += "/#{params[:id]}" if params[:id]
path += "/#{params[:sha]}" if params[:sha]
path
end
in the expiring method:
expire_fragment "serve/up/#{#site.id}"
expire_fragment "serve/fresh/#{#site.secret}"

Rails 3 assertions failure message: "Expected block to return true value" not helpful; what gives?

This occurs frequently in my controller and route tests. Example, given the route
match "/about", :to => "about#profile"
And the test
test "/about goes to about/profile" do
assert_generates "/about/", { :controller => "about", :action => "profile" }
end
The only failure message is "Expected block to return true value". This happens also with tests like:
test "bills should redirect to /bills" do
get :bills
assert_redirected_to user_bills_path(#user)
end
If my controller doesn't' redirect to user_bills_path(#user), I get the same error: "Expected block to return true value"
This is very annoying for test-driving, as I cannot easily check that my assertion is failing before writing production code or failing because I've written the incorrect test.
It seems to be coming from Rails testing stuff. Any way to avoid this or get better messages?

How do I write a Rails 3.1 engine controller test in rspec?

I have written a Rails 3.1 engine with the namespace Posts. Hence, my controllers are found in app/controllers/posts/, my models in app/models/posts, etc. I can test the models just fine. The spec for one model looks like...
module Posts
describe Post do
describe 'Associations' do
it ...
end
... and everything works fine.
However, the specs for the controllers do not work. The Rails engine is mounted at /posts, yet the controller is Posts::PostController. Thus, the tests look for the controller route to be posts/posts.
describe "GET index" do
it "assigns all posts as #posts" do
Posts::Post.stub(:all) { [mock_post] }
get :index
assigns(:posts).should eq([mock_post])
end
end
which yields...
1) Posts::PostsController GET index assigns all posts as #posts
Failure/Error: get :index
ActionController::RoutingError:
No route matches {:controller=>"posts/posts"}
# ./spec/controllers/posts/posts_controller_spec.rb:16
I've tried all sorts of tricks in the test app's routes file... :namespace, etc, to no avail.
How do I make this work? It seems like it won't, since the engine puts the controller at /posts, yet the namespacing puts the controller at /posts/posts for the purpose of testing.
I'm assuming you're testing your engine with a dummy rails app, like the one that would be generated by enginex.
Your engine should be mounted in the dummy app:
In spec/dummy/config/routes.rb:
Dummy::Application.routes.draw do
mount Posts::Engine => '/posts-prefix'
end
My second assumption is that your engine is isolated:
In lib/posts.rb:
module Posts
class Engine < Rails::Engine
isolate_namespace Posts
end
end
I don't know if these two assumptions are really required, but that is how my own engine is structured.
The workaround is quite simple, instead of this
get :show, :id => 1
use this
get :show, {:id => 1, :use_route => :posts}
The :posts symbol should be the name of your engine and NOT the path where it is mounted.
This works because the get method parameters are passed straight to ActionDispatch::Routing::RouteSet::Generator#initialize (defined here), which in turn uses #named_route to get the correct route from Rack::Mount::RouteSet#generate (see here and here).
Plunging into the rails internals is fun, but quite time consuming, I would not do this every day ;-) .
HTH
I worked around this issue by overriding the get, post, put, and delete methods that are provided, making it so they always pass use_route as a parameter.
I used Benoit's answer as a basis for this. Thanks buddy!
module ControllerHacks
def get(action, parameters = nil, session = nil, flash = nil)
process_action(action, parameters, session, flash, "GET")
end
# Executes a request simulating POST HTTP method and set/volley the response
def post(action, parameters = nil, session = nil, flash = nil)
process_action(action, parameters, session, flash, "POST")
end
# Executes a request simulating PUT HTTP method and set/volley the response
def put(action, parameters = nil, session = nil, flash = nil)
process_action(action, parameters, session, flash, "PUT")
end
# Executes a request simulating DELETE HTTP method and set/volley the response
def delete(action, parameters = nil, session = nil, flash = nil)
process_action(action, parameters, session, flash, "DELETE")
end
private
def process_action(action, parameters = nil, session = nil, flash = nil, method = "GET")
parameters ||= {}
process(action, parameters.merge!(:use_route => :my_engine), session, flash, method)
end
end
RSpec.configure do |c|
c.include ControllerHacks, :type => :controller
end
Use the rspec-rails routes directive:
describe MyEngine::WidgetsController do
routes { MyEngine::Engine.routes }
# Specs can use the engine's routes & named URL helpers
# without any other special code.
end
– RSpec Rails 2.14 official docs.
Based on this answer I chose the following solution:
#spec/spec_helper.rb
RSpec.configure do |config|
# other code
config.before(:each) { #routes = UserManager::Engine.routes }
end
The additional benefit is, that you don't need to have the before(:each) block in every controller-spec.
Solution for a problem when you don't have or cannot use isolate_namespace:
module Posts
class Engine < Rails::Engine
end
end
In controller specs, to fix routes:
get :show, {:id => 1, :use_route => :posts_engine}
Rails adds _engine to your app routes if you don't use isolate_namespace.
I'm developing a gem for my company that provides an API for the applications we're running. We're using Rails 3.0.9 still, with latest Rspec-Rails (2.10.1). I was having a similar issue where I had defined routes like so in my Rails engine gem.
match '/companyname/api_name' => 'CompanyName/ApiName/ControllerName#apimethod'
I was getting an error like
ActionController::RoutingError:
No route matches {:controller=>"company_name/api_name/controller_name", :action=>"apimethod"}
It turns out I just needed to redefine my route in underscore case so that RSpec could match it.
match '/companyname/api_name' => 'company_name/api_name/controller_name#apimethod'
I guess Rspec controller tests use a reverse lookup based on underscore case, whereas Rails will setup and interpret the route if you define it in camelcase or underscore case.
It was already mentioned about adding routes { MyEngine::Engine.routes }, although it's possible to specify this for all controller tests:
# spec/support/test_helpers/controller_routes.rb
module TestHelpers
module ControllerRoutes
extend ActiveSupport::Concern
included do
routes { MyEngine::Engine.routes }
end
end
end
and use in rails_helper.rb:
RSpec.configure do |config|
config.include TestHelpers::ControllerRoutes, type: :controller
end