Rspec:如何在控制器规范中分配实例变量 [英] Rspec: How to assign instance variable in controller spec

查看:53
本文介绍了Rspec:如何在控制器规范中分配实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class TestController < AplicationController
  #....

  private

  def some_method
    unless @my_variable.nil?
      #...
      return true
    end
  end
end

我想直接在控制器规范中测试 some_method:

I want to test some_method directly in controller spec:

require 'spec_helper'

describe TestController do
  it "test some_method"
    phone = Phone.new(...)
    controller.assign(:my_variable,phone) #does not work
    controller.send(:some_method).should be_true
  end
end

如何从控制器规范中设置 TestController 实例变量 @my_variable?

How I can set TestController instance variable @my_variable from controller spec?

推荐答案

在控制器中测试私有方法时,我倾向于使用 匿名控制器,因为不想直接调用私有方法,而是调用私有方法(或者,在下面的测试中,有效地存根该接口).所以,在你的情况下,也许是这样的:

When testing private methods in controllers, rather than use send, I tend to use an anonymous controller due to not wanting to call the private method directly, but the interface to the private method (or, in the test below, effectively stubbing that interface). So, in your case, perhaps something like:

require 'spec_helper'

describe TestController do
  controller do
    def test_some_method
      some_method
    end
  end

  describe "a phone test with some_method" do

    subject { controller.test_some_method }

    context "when my_variable is not nil" do
      before { controller.instance_variable_set(:@my_variable, Phone.new(...)) }
      it { should be_true }
    end

    context "when my_variable is nil" do
      before { controller.instance_variable_set(:@my_variable, nil) } 
      it { should_not be_true } # or should be_false or whatever
    end     
  end
end

这个 StackOverflow Q&A 中对直接测试私有方法的问题有一些很好的讨论,这让我倾向于使用匿名控制器,但您的意见可能会有所不同.

There's some good discussion on the issue of directly testing private methods in this StackOverflow Q&A, which swayed me towards using anonymous controllers, but your opinion may differ.

这篇关于Rspec:如何在控制器规范中分配实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆