0

我正在阅读railstutorial 第 5.6.4 章

根据页面,以下两个代码用于相同的测试。但是我不明白为什么没有论点它会起作用page_title"foo"Rspec中的字符串有特殊含义吗?

spec/support/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

spec/helpers/application_helper_spec.rb

require 'spec_helper'

describe ApplicationHelper do

  describe "full_title" do
    it "should include the page title" do
      expect(full_title("foo")).to match(/foo/)
    end

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

    it "should not include a bar for the home page" do
      expect(full_title("")).not_to match(/\|/)
    end
  end
end

spec/support/utilities.rb

include ApplicationHelper
4

2 回答 2

1

不,该字符串"foo"对 RSpec 没有任何特殊含义,它只是在测试中用作示例,以检查full_title帮助程序是否正常工作。

要回答您问题的另一部分,如果没有传入页面标题,则 if 语句将采用第一个路径,因为page_title变量为空,您将仅返回基本标题。以下是每个测试实际执行的操作:

# This is expected to return "Ruby on Rails Tutorial Sample App | foo", which
# will match /foo/.
it "should include the page title" do
  expect(full_title("foo")).to match(/foo/)
end

# This returns the same as above ("Ruby on Rails Tutorial Sample App | foo"),
# but this test is checking for the base title part instead of the "foo" part.
it "should include the base title" do
  expect(full_title("foo")).to match(/^Ruby on Rails Tutorial Sample App/)
end

# This returns just "Ruby on Rails Tutorial Sample App" because the page title
# is empty. This checks that the title doesn't contain a "|" character but that
# it only returns the base title.
it "should not include a bar for the home page" do
  expect(full_title("")).not_to match(/\|/)
end
于 2013-11-13T00:23:05.410 回答
1

这是可能对您有所帮助的测试的“rspec to English”翻译:

如果我给full_title方法 string "foo",结果应该:

  • 包含"foo"
  • 包含基本标题,即"Ruby on Rails Tutorial Sample App"
  • 不是"|"

测试背后的想法是确保您的代码使用一些有意义的代码行为示例来工作。您无法测试所有可能的场景,因此您选择一个(或多个)最能描述您的方法功能的场景。

在这种情况下,它传递一个字符串参数"foo",该参数通常用作编程中的占位符。

于 2013-11-13T00:31:41.597 回答