3

我有许多视图规范需要对某些方法进行存根。这是我认为可行的方法(在 spec_helper.rb 中):

Spec::Runner.configure do |config|
  config.before(:each, :type => :views) do
      template.stub!(:request_forgery_protection_token)
      template.stub!(:form_authenticity_token)
  end
end

但是当我运行任何视图规范时,它会失败

You have a nil object when you didn't expect it! The error occurred while evaluating nil.template

在每个示例的 before(:each) 块中执行完全相同的操作效果很好。

4

1 回答 1

3

我尝试了您的示例,发现与视图规范文件中的“之前”块相比,在“config.before”块中,RSpec 视图示例对象尚未完全初始化。因此,在“config.before”块中,“模板”方法返回 nil,因为模板尚未初始化。您可以通过在这两个块中包含例如“puts self.inspect”来查看它。

在您的情况下,实现 DRYer 规范的一种解决方法是在 spec_helper.rb 中定义

规格 2

module StubForgeryProtection
  def stub_forgery_protection
    view.stub(:request_forgery_protection_token)
    view.stub(:form_authenticity_token)
  end
end

RSpec.configure do |config|
  config.include StubForgeryProtection
end

规格 1

module StubForgeryProtection
  def stub_forgery_protection
    template.stub!(:request_forgery_protection_token)
    template.stub!(:form_authenticity_token)
  end
end

Spec::Runner.configure do |config|
  config.before(:each, :type => :views) do
    extend StubForgeryProtection
  end
end

然后在要使用此存根的每个 before(:each) 块中包括

before(:each) do
  # ...
  stub_forgery_protection
  # ...
end
于 2008-12-22T22:23:04.883 回答