简体   繁体   English

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

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

I have a number of view specs that need certain methods to be stubbed. 我有许多视图规范需要某些方法来存根。 Here's what I thought would work (in spec_helper.rb): 这是我认为可行的(在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

But when I run any view spec it fails with 但是,当我运行任何视图规范时,它失败了

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

Doing the exact same thing in the before(:each) block of each example works great. 在每个示例的before(:each)块中执行完全相同的操作非常有效。

I tried out your example and found out that in "config.before" block RSpec view example object is not yet fully initialized compared to "before" block in view spec file. 我试用了你的例子,发现在“config.before”块中,与视图spec文件中的“before”块相比,RSpec视图示例对象尚未完全初始化。 Therefore in "config.before" block "template" method returns nil as template is not yet initialized. 因此在“config.before”块中,“template”方法返回nil,因为模板尚未初始化。 You can see it by including eg "puts self.inspect" in both these blocks. 您可以通过在这两个块中包含例如“puts self.inspect”来查看它。

In your case one workaround for achieving DRYer spec would be to define in spec_helper.rb 在您的情况下,实现DRYer规范的一种解决方法是在spec_helper.rb中定义

RSpec 2 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 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

and then in each before(:each) block where you want to use this stubs include 然后在每个你想要使用这个存根包含的前(:每个)块中

before(:each) do
  # ...
  stub_forgery_protection
  # ...
end

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

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