作者Michael Hartl说:
这里的规则是:
get "static_pages/home"
将URI / static_pages / home的请求映射到StaticPages控制器中的home操作。
如何?给出了请求的类型,给出了url,但是到控制器和操作的映射在哪里?不过,我的测试都通过了。
我还尝试删除StaticPagesController中的所有操作,它们看起来像这样:
class StaticPagesController < ApplicationController
def home
end
def about
end
def help
end
def contact
end
end
......我的测试仍然通过,这令人费解。不,我删除了这样的所有动作:
class StaticPagesController < ApplicationController
end
本书的第2版(在线)非常令人沮丧。具体来说,关于对Guardfile进行更改的部分是不可能遵循的。例如,如果我指示您编辑此文件:
blah blah blah
dog dog dog
beetle beetle beetle
jump jump jump
并进行以下更改:
blah blah blah
.
.
.
go go go
.
.
.
jump jump jump
...你知道代码中的'go go go'应该在哪里?
3.5-1的运动暗示是错误的。如果作者在每章的末尾都会提出评论部分,那么rails社区可以自行编辑该书。
试验:
require 'spec_helper'
describe "StaticPages" do
let(:base_title) { "Ruby on Rails Tutorial Sample App" }
describe "Home page" do
it "should have the h1 'Sample App'" do
visit '/static_pages/home'
page.should have_selector('h1', :text => 'Sample App')
end
it "should have the title 'Home'" do
visit "/static_pages/home"
page.should have_selector(
'title',
:text => "#{base_title} | Home")
end
end
describe 'Help page' do
it "should have the h1 'Help'" do
visit "/static_pages/help"
page.should have_selector('h1', :text => 'Help')
end
it "should have the title 'Help'" do
visit '/static_pages/help'
page.should have_selector(
'title',
:text => "#{base_title} | Help")
end
end
describe 'About page' do
it "should have the h1 'About'" do
visit '/static_pages/about'
page.should have_selector('h1', :text => 'About')
end
it "should have the title 'About'" do
visit '/static_pages/about'
page.should have_selector(
'title',
:text => "#{base_title} | About")
end
end
describe 'Contact page' do
it "should have the h1 'Contact'" do
visit '/static_pages/contact'
page.should have_selector('h1', :text => 'Contact')
end
it "should have the title 'Contact'" do
visit '/static_pages/contact'
page.should have_selector(
'title',
:text => "#{base_title} | Contact")
end
end
end
答案 0 :(得分:1)
正如你在这里看到的那样:
http://guides.rubyonrails.org/routing.html#http-verb-constraints
这只是
的简写match 'static_pages/home' => 'static_pages#home', :via => :get
基本上Rails从您的网址static_pages/home
推断出您指的是StaticPagesController的主页操作。
此外,当您“删除”所有操作时,您会离开操作定义 - 这是测试检查的内容。它只是检查它是否可以进入staticpages控制器的home操作。如果它什么也不做就没有关系,只要它存在(至少我认为你的测试确实如此 - 也要关注测试?)
如果删除
...
def home
end
...
从您的控制器,我很确定您的测试将失败
答案 1 :(得分:0)
我找到了这个难题的答案。首先,这是一个轨道'问题'而不是一个rspec问题;如果我添加路由到routes.rb,例如:
get "static_pages/dog"
...然后输入网址
http://localhost:3000/static_pages/dog
在我的浏览器中,rails抱怨:
未知行动
无法为StaticPagesController找到动作'dog'
然后,如果我将狗动作添加到控制器,然后创建一个视图, 一切都很好,花花公子。
但是,如果我然后删除狗动作,然后使用相同的URL,
http://localhost:3000/static_pages/dog
在我的浏览器中,这次我得到了不同的结果 - 而不是显示视图的错误。
事实证明,这种不一致的行为是一个称为默认渲染的rails'功能',在此解释:
根据文档,呈现页面所需的全部内容是路径和视图 - 操作是可选的。