【问题标题】:RSpec mocking module function of controller控制器的RSpec模拟模块功能
【发布时间】:2016-06-23 00:36:59
【问题描述】:

所以我对 Rails 非常陌生,并且在使用 RSpec 时遇到了一些困难,特别是嘲笑某些事情。所以我有一个我的一些控制器正在使用的模块(关注点)。该模块 (ValidateAdmin) 调用其中的另外两个函数 current_user 和 logged_in_user。为了涵盖大多数可能性,我想存根这两个函数并设置它们的返回值。关于如何使这项工作的任何建议?

describe ValidateAdmin do
  before :all do
    class FakeController < ApplicationController
      include ValidateAdmin
    end
  end

let(:controller) { FakeController.new }

describe '#validate_admin_logged_in' do
  controller.stub(:current_user).and_return(instance_double(User, admin?: true))
  controller.stub(:logged_in_user).and_return(instance_double(User, admin?: true))
  [RSpec contexts go here]

编辑 - 通过在“之前”块中包含我的模拟语句来修复它。也刚刚意识到存根已被弃用,因此切换到允许语句。

【问题讨论】:

  • 您当前的代码现在会发生什么?
  • @MohammadAbuShady 很抱歉没有把它放在问题中,我有点匆忙。它抛出了一个非常奇怪的错误,尽管我通过将它包含在“之前”块中来修复它。我犯了一个愚蠢的错误,但感谢您的回复。

标签: ruby-on-rails ruby rspec


【解决方案1】:

控制器实例可以像任何其他对象一样被存根。您可能还需要添加路线:

describe FakeController, type: :controller do
  let(:admin_user) { instance_double(User, admin?: true) }

  it "performs my excellent test" do
    allow(controller).to receive(:current_user).and_return(admin_user)
    routes.draw { get "custom_action" => "fake#custom_action" }
    get :custom_action
  end
end

let(:controller) 是不必要的——RSpec 会为你做到这一点。此外,测试类不需要进入before 块——它可以简单地在文件顶部定义,或者 require-d。

【讨论】:

  • 我的问题在于我的存根语句的位置 - 通过将它放在“之前”块中修复了我遇到的奇怪错误。也从存根更改为允许,因为我发现它已被弃用。谢谢!
猜你喜欢
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
  • 2013-05-06
  • 1970-01-01
  • 2013-08-04
  • 2019-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多