【问题标题】:Can I mock out an included module?我可以模拟一个包含的模块吗?
【发布时间】:2014-02-04 06:03:50
【问题描述】:

当一个模块被显式包含时,它很容易模拟出来,就像这样:

class MyController < ApplicationController
    MyHelper.sometimes_true_sometimes_false
end

在规范中,你只需写:

MyHelper.should_receive(:sometimes_true_sometimes_false).and_return true

在上下文中:

模块

module MyHelper
    def sometimes_true_sometimes_false
        [true, false].sample
    end
end

控制器

class MyController < ApplicationController
    def myaction
        if MyHelper.sometimes_true_sometimes_false
            @message = "Congratualtions, it's true"
        else
            @message = "Sorry, it's false"
        end
    end
end

规格

describe 'GET #myaction'
    subject { get :myaction }
    context 'when it\'s true' do
        before do
             MyHelper.should_receive(:sometimes_true_sometimes_false).and_return true
        end
        specify { expect(assigns(:message)).to eq "Congratulations, it's true" }
    end
    context 'when it\'s false' do
        before do
             MyHelper.should_receive(:sometimes_true_sometimes_false).and_return false
        end
        specify { expect(assigns(:message)).to eq "Sorry, it's true" }
    end
end

但是当模块包含在控制器中时,我应该如何编写规范,以及本机调用的类方法,如下所示:

class MyController < ApplicationController
    include MyHelper

    sometimes_true_sometimes_false
end

在上下文中:

控制器

class MyController < ApplicationController
    include MyHelper

    def myaction
        if sometimes_true_sometimes_false
            @message = "Congratualtions, it's true"
        else
            @message = "Sorry, it's false"
        end
    end
end

【问题讨论】:

    标签: unit-testing rspec mocking


    【解决方案1】:

    实际上很简单,在我创建答案时想到了答案(并且对标题标签进行了思考):

    你只需写:

    MyController.any_instance.should_receive(:sometimes_true_sometimes_false).and_return true
    

    规格

    describe 'GET #myaction'
        subject { get :myaction }
        context 'when it\'s true' do
            before do
                 MyController.any_instance.should_receive(:sometimes_true_sometimes_false).and_return true
            end
            specify { expect(assigns(:message)).to eq "Congratulations, it's true" }
        end
        context 'when it\'s false' do
            before do
                 MyController.any_instance.should_receive(:sometimes_true_sometimes_false).and_return false
            end
            specify { expect(assigns(:message)).to eq "Sorry, it's true" }
        end
    end
    

    【讨论】:

      猜你喜欢
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 2021-05-01
      • 2014-01-18
      • 2018-09-27
      • 1970-01-01
      相关资源
      最近更新 更多