繁体   English   中英

使用rspec-rails在所有视图规范上存根模板方法的正确方法是什么?

[英]What is the correct way to stub template methods on all view specs using rspec-rails?

我有许多视图规范需要某些方法来存根。 这是我认为可行的(在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)块中执行完全相同的操作非常有效。

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

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

RSpec 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

RSpec 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) do
  # ...
  stub_forgery_protection
  # ...
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM