【问题标题】:How to access the describe text in rspec如何访问 rspec 中的描述文本
【发布时间】:2019-10-18 21:10:33
【问题描述】:

我正在编写一些规范来测试具有 Rails 生成器的 gem 中的模板文件。我很想在下面的 rspec 规范中访问“admin_layout.html.erb”:

require 'spec_helper'

describe "admin_layout.html.erb" do

  it "has page title Admin" do
     HERES WHERE I WOULD LOVE TO HAVE ACCESS TO "admin_layout.html.erb" AS A VARIABLE
  end

end

【问题讨论】:

  • 我很好奇,这会让你做什么?
  • 我正在 Rails 中构建一个管理生成器,我正在尝试测试一些关于我正在编写的生成器使用的模板内容的基础知识

标签: ruby rspec


【解决方案1】:

您可以使用self.class.description 获取此信息:

it "has page title Admin" do
  layout = self.class.description 
  # => "admin_layout.html.erb"
end

但是,请记住,这只会显示第一个父母的描述。因此,如果您的 describe 块中有上下文,那么上下文中的示例将给出 self.class 的上下文名称,而不是 describe 块的名称。在这种情况下,您可以使用元数据:

describe "admin_layout.html.erb", :layout => "admin_layout.html.erb"
  context "foo" do
    it "has page title Admin" do
      layout = example.metadata[:layout]
    end
  end
end

如果你想要顶级描述,你可以使用self.class.top_level_description:

RSpec.describe "Foo", type: :model do
  context "bar" do
    it "is part of Foo" do
      self.class.top_level_description
      # => "Foo"
    end
  end
end

【讨论】:

  • 在 RSpec 3 中,使用RSpec.current_example.metadata[...]。见this issue
  • 在 RSpec 3 中,要获取顶级描述(即“admin_layout.html.erb”),您可以使用self.class.top_level_description
猜你喜欢
  • 2018-01-28
  • 2011-03-31
  • 2018-06-18
  • 1970-01-01
  • 2021-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多