测试 - rspec Hartl教程,第5.33章

时间:2012-06-05 22:46:48

标签: ruby-on-rails rspec railstutorial.org

我在测试尝试创建登录页面时遇到了同样的两个失败。

以下是错误消息: $ bundle exec rspec spec / requests / user_pages_spec.rb FF

故障:

1)用户页面注册页面      失败/错误:{visit signup_path}之前      ::的ActionView ::模板错误:        未定义的方法|' for "Ruby on Rails Tutorial Sample App":String # ./app/helpers/application_helper.rb:9:in full_title'      './app/views/layouts/application.html.erb:4:in _app_views_layouts_application_html_erb__2148911516627374684_2168968760' # ./spec/requests/user_pages_spec.rb:8:in阻止(3级)'

2)用户页面注册页面      失败/错误:{visit signup_path}之前      ::的ActionView ::模板错误:        未定义的方法|' for "Ruby on Rails Tutorial Sample App":String # ./app/helpers/application_helper.rb:9:in full_title'      './app/views/layouts/application.html.erb:4:in _app_views_layouts_application_html_erb__2148911516627374684_2168968760' # ./spec/requests/user_pages_spec.rb:8:in阻止(3级)'

以0.17668秒结束 2个例子,2个失败

失败的例子:

rspec ./spec/requests/user_pages_spec.rb:10#用户页面注册页面 rspec ./spec/requests/user_pages_spec.rb:11#用户页面注册页面

以下是文件user_pages_spec.rb

要求'spec_helper'

描述“用户页面”

subject {page}

描述“注册页面”     在{visit signup_path}之前

it { should have_selector('h1', text: 'Sign up') }
it { should have_selector('title', text: full_title('Sign up')) }

端 端

这里是文件application_helper.rb:

模块ApplicationHelper

  # Returns the full title on a per-page basis.
  def full_title(page_title)
    base_title = "Ruby on Rails Tutorial Sample App"
    if page_title.empty?
      base_title
    else
      "#{base_title}" | "#{page_title}"
    end
  end
end

这里是文件routes.rb         SampleApp :: Application.routes.draw做           得到“用户/新”

  root to: 'static_pages#home'

  match '/signup',  to: 'users#new'

  match '/help',    to: 'static_pages#help'
  match '/about',   to: 'static_pages#about'
  match '/contact', to: 'static_pages#contact'

我一直坚持这一点,所以任何帮助都将不胜感激!

谢谢!

2 个答案:

答案 0 :(得分:0)

它为您提供的rails错误消息非常具有描述性。

如果我们看一下

undefined method `|' for "Ruby on Rails Tutorial Sample App":String # ./app/helpers/application_helper.rb:9:in full_title

它告诉我们它无法在|方法定义中的application_helper.rb的第9行找到名为"Ruby on Rails Tutorial Sample App"的方法{@ 1}}。如果我们到达那条线,我们可以看到

full_title

哪个ruby解释为“在#{base_title}”的结果上运行方法|在这种情况下,使用参数“#{page_title}”计算字符串“Ruby on Rails Tutorial Sample App”。由于字符串没有'|'方法,它返回一个“未定义的方法”错误。

要修复,只需将行更改为

即可
 "#{base_title}" | "#{page_title}"

答案 1 :(得分:0)

这一行:

     "#{base_title}" | "#{page_title}"

是罪魁祸首。

我会为你分解错误信息(你会想要擅长阅读这些):

 ActionView::Template::Error: undefined method |' for "Ruby on Rails Tutorial Sample App":String # 

这说明ActionView模板系统在运行帮助程序时遇到了麻烦。具体来说,它说你试图调用一个名为'|'的未定义方法(类方法的名称是管道字符)在String类的对象上。

如果您查看String类的文档here,您会看到方法'|'不在可用方法列表中。

我的猜测是你试图将这些连接在一起并包含管道字符,就像面包屑一样。在这种情况下,您只需将整行包含在引号中,如下所示:

     "#{base_title} | #{page_title}"
祝你好运!