Testing Rails controller action with no direct route
I am building my own blog in order to learn rails3.
Need my URLs to be formatted to:
/blog/year/month/slug
So I have my routes.rb set up as this:
Blog::Application.routes.draw do
match '/blog', :to => 'post#index'
match 'blog/:year/:month/:slug', :to => 'post#show'
root :to => 'post#index'
...
Testing this via a web browser works great. The problem comes in when I want to test my PostController's show
action method.
When I execute this test:
class PostControllerTest < ActionController::TestCase
test "can get a post by slug" do
get :show
assert_response :success
end
e开发者_运维百科nd
I get this error:
ActionController::RoutingError: No route matches {:controller=>"post", :action=>"show"}
How can I write my test so I can execute the show action method in my Post controller?
This is at least expecting there to be a year
, month
and slug
parameter to be set. Your routes require that much, at least.
In your test:
test "can get a post by slug" do
post = Post.create(:slug => "best-post-ever")
get :show, :slug => post.slug, :year => Time.now.year, :month => Time.now.month
assert_response :success
end
With these three parameters, the route will now be matched and your request will go through.
精彩评论