简体   繁体   中英

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::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.

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. Therefore in "config.before" block "template" method returns nil as template is not yet initialized. You can see it by including eg "puts self.inspect" in both these blocks.

In your case one workaround for achieving DRYer spec would be to define in 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

and then in each before(:each) block where you want to use this stubs include

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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