2016-06-21 62 views
0

所以我对Rails非常陌生,并且在RSpec中挣扎了一番,特别是嘲笑某些事情。所以我有一个模块(关注),我的一些控制器正在使用。该模块(ValidateAdmin)在current_user和logged_in_user中调用另外两个函数。为了覆盖最多的可能性,我想将这两个函数存根并设置它们的返回值。有关如何完成这项工作的任何建议?控制器的RSpec嘲讽模块功能

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] 

编辑 - 修正它包含我之前的'块'的模拟语句。也只是实现存根被弃用,所以切换到允许语句。

+0

现在使用你当前的代码会发生什么? –

+0

@MohammadAbuShady对不起,没有把这个问题,我有点匆忙。它抛出了一个非常奇怪的错误,尽管我通过将它包含在'before'块中来解决它。愚蠢的错误在我的部分,但感谢您的回应。 – jdune

回答

0

控制器实例可以像任何其他对象一样被桩起来。您可能还需要添加路由:

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)是uneccessary - RSpec的这是否为您服务。此外,测试类不需要进入before块 - 它可以简单地定义在文件的顶部,或者需要-d。

+0

我的问题是我在哪里有我的存根语句 - 修正了我通过将它放在'before'块中而得到的奇怪错误。也从存根更改为允许,因为我发现已弃用。谢谢! – jdune