【发布时间】:2018-02-05 02:48:56
【问题描述】:
我正在尝试为 Rails 助手编写规范。这个助手调用一个方法
在ApplicationController 中定义并通过helper_method 公开:
app/helpers/monkeys_helper.rb:
module MonkeysHelper
def current_monkey_banana_count
# current_monkey is defined in ApplicationController
current_monkey.present? ? current_monkey.banana_count : 0
end
end
app/controllers/application_controller.rb:
class ApplicationController < ActionController::Base
helper_method :current_monkey
protected
def current_monkey
@current_monkey ||= Monkey.find(session[:monkey_id])
end
end
如果我从视图中调用current_monkey_banana_count 并通过浏览器访问它,它可以正常工作。但如果我从这样的规范中调用它:
spec/helpers/monkeys_helper_spec.rb:
RSpec.describe MonkeysHelper, type: :helper do
describe "#current_monkey_banana_count" do
it "returns 0 if there is no monkey" do
expect(helper.current_monkey_banana_count).to eq 0
end
end
end
然后我在运行规范时收到此错误:
NameError:
undefined local variable or method `current_monkey' for #<#<Class:0x007fe1ed38d700>:0x007fe1e9c72d88>
要访问您指定的辅助方法,只需调用它们 直接在辅助对象上。注意:在中定义的辅助方法 不包括控制器。
知道如何模拟current_monkey 或使其在current_monkey_banana_count 内部可见吗?
谢谢!
【问题讨论】:
标签: ruby-on-rails rspec