【问题标题】:Set local variable rspec helper设置局部变量 rspec 助手
【发布时间】:2016-03-11 19:00:13
【问题描述】:

我正在尝试通过 rspec 在视图助手中设置局部变量。我的日常是这样的

def time_format(time)
    now = Time.now.in_time_zone(current_user.timezone)
end

我的规范文件如下:

it 'return 12 hour format' do
      user = User.first
      assign(:current_user, user)
      expect(helper.time_format(900)).to eq('9:00 AM')
end

规范失败并抛出错误未定义的局部变量或方法'current_user'

'current_user' 驻留在 application_controller 中

【问题讨论】:

    标签: ruby-on-rails ruby rspec helper


    【解决方案1】:

    问题

    您的 current_user 方法在您的 rspec 测试中不可用。这就是您收到上述错误的原因。

    解决方案

    您可以在测试助手中实现current_user 方法,然后在测试中使用它,或者您可以像这样在规范测试中存根current_user

    let(:user) { User.new }
    
    # RSpec version >= 3 syntax:
    before { allow(controller).to receive(:current_user) { user } }
    before { allow(view).to receive(:current_user) { user } }
    
    # RSpec version <= 2 syntax:
    before { controller.stub(:current_user) { user } }
    before { view.stub(:current_user) { user } }
    

    这应该可以解决您的问题。

    另外,如果您使用devise 进行身份验证,那么我建议您查看:How To: Test controllers with Rails 3 and 4 (and RSpec)

    【讨论】:

    • 感谢您的回复,但我仍然卡在那里。我已经使用了你的解决方案,它给我扔了一个长长的堆栈,以这个语句“不实现:current_user”结尾。我也试过'allow_any_instance_of',它给我这个错误:“NoMethodError: undefined method `ancestors' for #:0x0000000991f4c0>”
    • 为什么卡住了?你试过我的建议了吗?
    猜你喜欢
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    相关资源
    最近更新 更多