ruby-on-rails - 在助手规范中测试当前用户

标签 ruby-on-rails testing rspec helper

我有这个非常基本的助手,它依赖于 Sorcery 在 Controller 和助手中提供的 current_user 变量

def current_user_link
    user_link current_user
end

 def user_link(user, html_options = {}, &block)
   link_to user.to_s, user, html_options, &block
 end

如何测试这个助手?

describe UsersHelper do
  describe '#current_user_link' do
    it 'should return a link to the current user' do
      expected_link = link_to current_user.name, current_user
      ???

      expect(current_user_link).to eq expected_link
    end
  end

我需要以某种方式 stub current_user 吗? 它甚至值得测试吗?

最佳答案

我就是这样解决的。

describe '#current_user_link' do
  it 'returns a link to the current user ' do
    user = build(:user)
    expected_link = link_to user.name, user
    allow(controller).to receive(:current_user).and_return(user)

    expect(helper.current_user_link).to eq(expected_link)
  end
end

PSA:不要忘记在helper 上调用您的方法。

关于ruby-on-rails - 在助手规范中测试当前用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34904378/

相关文章:

ruby-on-rails - 即使使用来自 bisect 的最小再现命令,Rspec 也无法再现故障

c# - 使用 Raven Db 进行边界测试

ruby-on-rails - rails : RSpec: using global path variables only seems to work within "it" blocks

php - 在 Laravel 中针对 MySQL 进行测试

ruby - 如何从factory_girl create 返回现有实例?

ruby-on-rails - Rails - 在本地主机上创建内部服务器错误 (500)

ruby-on-rails - 用符号转换哈希数组

ruby-on-rails - 使用 Rails paths.rb 文件生成 API 引用文档的最佳方法是什么?

jquery - 您会在 Rails 应用程序中使用什么来自动完成?

ruby-on-rails - FactoryGirl 创作不会出现在 Selenium 测试中