Ruby on rails Rails:RSpec:使用全局路径变量似乎只在“内部”中起作用;它";阻碍

Ruby on rails Rails:RSpec:使用全局路径变量似乎只在“内部”中起作用;它";阻碍,ruby-on-rails,ruby,testing,rspec,rspec-rails,Ruby On Rails,Ruby,Testing,Rspec,Rspec Rails,在学习Michael Hartl的Rails教程时,我在测试部分尝试了一些自定义函数,遇到了一个令我惊讶的限制。基本上,全局路径变量(例如“root_path”)只在RSpec测试的“描述”块中的“it”部分的“do…end”块中起作用 我相信下面的细节可以归结为一个问题,“it”块有什么特别之处,它使“root_path”能够在那里工作,而不在“it”块之外工作 (我已经确定了解决办法,但我很好奇是否有可靠的解释来解释这种行为。) 文件:spec/requests/static\u pages

在学习Michael Hartl的Rails教程时,我在测试部分尝试了一些自定义函数,遇到了一个令我惊讶的限制。基本上,全局路径变量(例如“root_path”)只在RSpec测试的“描述”块中的“it”部分的“do…end”块中起作用

我相信下面的细节可以归结为一个问题,“it”块有什么特别之处,它使“root_path”能够在那里工作,而不在“it”块之外工作

(我已经确定了解决办法,但我很好奇是否有可靠的解释来解释这种行为。)

文件:spec/requests/static\u pages\u spec.rb

此操作失败:

require 'spec_helper'

def check_stable(path)
  it "should be stable" do
    get path
    response.status.should be(200)
  end
end

describe "StaticPages" do
  describe "Home => GET" do
    check_stable(root_path)
  end
end
require 'spec_helper'

describe "StaticPages" do
  describe "Home => GET" do
    it "should be stable" do
      get root_path
      response.status.should be(200)
    end
  end
end
成功:

require 'spec_helper'

def check_stable(path)
  it "should be stable" do
    get path
    response.status.should be(200)
  end
end

describe "StaticPages" do
  describe "Home => GET" do
    check_stable(root_path)
  end
end
require 'spec_helper'

describe "StaticPages" do
  describe "Home => GET" do
    it "should be stable" do
      get root_path
      response.status.should be(200)
    end
  end
end
故障基本上是:

$ bundle exec rspec spec/requests/static_pages_spec.rb
Exception encountered: #<NameError: undefined local variable or method `root_path' for #<Class:0x00000004cecd78>>
$bundle exec rspec spec/requests/static\u pages\u spec.rb

遇到异常:#是,命名路由仅在
it
specify
块内工作。但修改代码很容易:

def should_be_stable(path)
  get path
  response.status.should be(200)
end

describe "StaticPages" do
  describe "Home => GET" do
    it { should_be_stable(root_path) }
  end
end

您需要

块(或
指定
块)表示实际测试。在测试中,您将可以访问完整的Rails和Rspec助手;在测试之外,没有那么多(正如你所做的那样)。

。。。或者在
之前:每个do
之后的每个do
块内。公平点是:易于修改——我感谢您在演示调整的同时仍然保持“描述”中的一行测试。因此,也可以使子功能更精简。