【发布时间】:2011-05-20 00:11:51
【问题描述】:
我找不到任何解释如何在 Rails 3 中测试路由的内容。即使在 Rspec 书中,也没有很好地解释。
谢谢
【问题讨论】:
我找不到任何解释如何在 Rails 3 中测试路由的内容。即使在 Rspec 书中,也没有很好地解释。
谢谢
【问题讨论】:
rspec-rails Github site 上有一个简短的示例。您还可以使用脚手架生成器生成一些罐头示例。例如,
rails g scaffold Article
应该产生这样的东西:
require "spec_helper"
describe ArticlesController do
describe "routing" do
it "routes to #index" do
get("/articles").should route_to("articles#index")
end
it "routes to #new" do
get("/articles/new").should route_to("articles#new")
end
it "routes to #show" do
get("/articles/1").should route_to("articles#show", :id => "1")
end
it "routes to #edit" do
get("/articles/1/edit").should route_to("articles#edit", :id => "1")
end
it "routes to #create" do
post("/articles").should route_to("articles#create")
end
it "routes to #update" do
put("/articles/1").should route_to("articles#update", :id => "1")
end
it "routes to #destroy" do
delete("/articles/1").should route_to("articles#destroy", :id => "1")
end
end
end
【讨论】:
Zetetic 的回答解释了如何测试路线。这个答案解释了为什么你不应该这样做。
一般来说,您的测试应该测试暴露给用户(或客户端对象)的行为,而不是提供该行为的实现。路由是面向用户的:当用户输入http://www.mysite.com/profile 时,他并不关心它是否转到ProfilesController;相反,他关心的是看到他的个人资料。
所以不要测试你将要使用 ProfilesController。相反,设置一个 Cucumber 场景来测试当用户转到 /profile 时,他会看到他的姓名和个人资料信息。这就是你所需要的。
再次重申:不要测试您的路线。测试你的行为。
【讨论】: