views:

478

answers:

1

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.

+2  A: 

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 e.g. "puts self.inspect" in both these blocks.

In your case one workaround for achieving DRYer spec would be to define in spec_helper.rb

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
Raimonds Simanovskis
Thanks Raimonds, I ended up doing a similar thing, (btw, the @controller variable seems to not be initialized in the config, and template is defined as @controller.template, hence the error msg). This feels like a bug
Max Caceres