Ruby 控制器方法的书写测试
我在控制器中有一个受保护的方法,需要为它编写测试用例。方法是Ruby 控制器方法的书写测试,ruby,ruby-on-rails-3,minitest,Ruby,Ruby On Rails 3,Minitest,我在控制器中有一个受保护的方法,需要为它编写测试用例。方法是 def source @source.present? ? @source.class : Association.reflect_on_association(source.to_sym).klass end 其中@source将是一个对象,source将是一个字符串 我不知道如何为这种方法编写测试用例 edit 这就是我正在尝试的 subject { @controller } describe '#source' do
def source
@source.present? ? @source.class : Association.reflect_on_association(source.to_sym).klass
end
其中@source将是一个对象,source将是一个字符串
我不知道如何为这种方法编写测试用例
edit
这就是我正在尝试的
subject { @controller }
describe '#source' do
let(:source_object) { create :program_type}
describe "Object is not present" do
it 'should reflect on association and return the reflection class' do
subject.stubs(:source_identifier).returns("program_type")
subject.send(:source).must_equal ProgramType
end
end
describe "Object is present" do
it 'should return the class of the object' do
subject.send(:source).must_equal source_object.class
end
end
end
提前感谢。对于控制器测试,我有以下教程作为参考 1- 2-(更像一张乳酪纸)
然而,在我看来,您的方法应该转移到模型或库。(我只是通过查看您的代码来猜测)另一件事是,如果您无法隔离用于测试的方法,可能您必须重新考虑设计:)一般来说,我建议不要为受保护的控制器方法编写测试,它们应该由任何面向公众的方法调用 在您的情况下,只要您测试调用source的任何东西,您就将测试source 如果你真的需要,尽管你能做到
@controller = MyController.new
@controller.send(:source) #this will call source
我修好了。问题是第一个测试返回字符串,第二个测试返回对象。以下是我所做的修复
describe '#source' do
describe "Object is not present" do
it 'should reflect on association and return the reflection class' do
subject.stubs(:source_identifier).returns("program_types")
subject.send(:source).must_equal ProgramType
end
end
describe "Object is present" do
it 'should return the class of the object' do
subject.instance_variable_set(:@source, create(:program_type))
subject.send(:source).must_equal ProgramType
end
end
end
:-谢谢您的回答,但我将错误undefined_method改为_sym for nil:nilclass我想您已将MyController更改为控制器的名称?您能更新您的问题以显示您正在尝试的代码吗?