class TestController < AplicationController
#....
private
def some_method
unless @my_variable.nil?
#...
return true
end
end
end
我想测试some_method
直接在控制器规格中:
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
从控制器规格?
在控制器中测试私有方法时,而不是使用send
,我倾向于使用匿名控制者 https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs/anonymous-controller由于不想直接调用私有方法,而是调用私有方法的接口(或者,在下面的测试中,有效地存根该接口)。所以,就你而言,也许是这样的:
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 问答 https://stackoverflow.com/q/4271696/567863,这让我倾向于使用匿名控制器,但您的意见可能有所不同。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)