加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails-3 – Rails教程第5章练习3 – 原始的full_title函

发布时间:2020-12-17 02:34:20 所属栏目:百科 来源:网络整理
导读:我对第5章练习3 here感到困惑,它取代了对full_title测试助手的需求 规格/支持/ utilities.rb: def full_title(page_title) base_title = "Ruby on Rails Tutorial Sample App" if page_title.empty? base_title else "#{base_title} | #{page_title}" enden
我对第5章练习3 here感到困惑,它取代了对full_title测试助手的需求

规格/支持/ utilities.rb:

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

还有一个同名的rails helper函数:

module 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

通过创建一个直接测试函数的应用程序帮助程序:
规格/助理/ application_helper_spec.rb

require 'spec_helper'

describe ApplicationHelper do

 describe "full_title" do
   it "should include the page title" do
     full_title("foo").should =~ /foo/
   end

   it "should include the base title" do
     full_title("foo").should =~ /^Ruby on Rails Tutorial Sample App/
   end

   it "should not include a bar for the home page" do
     full_title("").should_not =~ /|/
   end
  end
end

这很好,它直接测试rails helper函数,但我认为utilities.rb中的完整title函数用于Rspec代码.因此,为什么我们可以在utilities.rb中删除上面的代码并用以下内容替换:

include ApplicationHelper

我做了交换,一切仍然有效.我期待Rspec代码,我虽然使用rspec函数,如下所示错误,但它没有:

it "should have the right links on the layout" do
  visit root_path
  click_link "About"
  page.should have_selector 'title',text: full_title('About Us')
  ...

以上函数调用是否总是指向实际的rails函数而不是respec函数?如果我能够消除它首先是什么?我觉得我在这里错过了一些东西.谢谢你的帮助.当我的目标是学习Rails时,似乎做出改变的坏主意我不明白.

谢谢,
标记

解决方法

specs中的full_title始终从spec / support / utilities.rb调用.

在使用include ApplicationHelper替换代码之前,规范中的full_title正在调用utilities.rb中的函数:

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

用just替换代码

include ApplicationHelper

要清楚,你实际上是包括在内

module ApplicationHelper

来自helpers / application_helper.rb.

这与在spec / helpers / application_helper_spec.rb中描述ApplicationHelper无关

真正发生的是模块ApplicationHelper的full_title函数现在是mixed in (see Mixins)到utilities.rb.因此,utilities.rb可以从模块ApplicationHelper(helpers / application_helper.rb)访问函数full_title.

因此,当specs调用full_title函数时,它会从utilities.rb中调用,这是可能的,因为函数已经通过使用include ApplicationHelper混入了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读