我有许多视图规范需要某些方法来存根。这是我认为可行的(在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)块中执行完全相同的操作非常有用。
答案 0 :(得分:3)
我试用了你的例子,发现在“config.before”块中,与视图spec文件中的“before”块相比,RSpec视图示例对象尚未完全初始化。因此在“config.before”块中,“template”方法返回nil,因为模板尚未初始化。你可以通过包括例如“将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