我正在建立自己的博客,以便学习rails3。
需要将我的网址格式化为:
/blog/year/month/slug
所以我将routes.rb设置为:
Blog::Application.routes.draw do
match '/blog', :to => 'post#index'
match 'blog/:year/:month/:slug', :to => 'post#show'
root :to => 'post#index'
...
通过网络浏览器进行测试非常有效。当我想测试我的PostController的show
动作方法时,会出现问题。
当我执行此测试时:
class PostControllerTest < ActionController::TestCase
test "can get a post by slug" do
get :show
assert_response :success
end
end
我收到此错误:
ActionController::RoutingError: No route matches {:controller=>"post", :action=>"show"}
如何编写测试以便在Post控制器中执行show action方法?
答案 0 :(得分:2)
这至少需要设置year
,month
和slug
参数。你的路线要求那么多,至少。
在你的测试中:
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
使用这三个参数,路线现在将匹配,您的请求将会通过。