【问题标题】:Writing test for controller method为控制器方法编写测试
【发布时间】:2014-07-30 19:54:41
【问题描述】:

我在控制器中有一个受保护的方法,需要为它编写测试用例。方法是

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

提前致谢。

【问题讨论】:

    标签: ruby ruby-on-rails-3 minitest


    【解决方案1】:

    对于测试控制器,我有以下教程作为参考

    1 - http://everydayrails.com/2012/04/07/testing-series-rspec-controllers.html

    2 - https://gist.github.com/delphaber/d898152eee04cea4964f(更像是一张小抄)

    但在我看来,您的方法应该转移到模型或库中。 (我只是通过查看您的代码来猜测)另一件事是,如果您无法隔离测试方法,可能您可能需要重新考虑设计:)

    【讨论】:

      【解决方案2】:

      一般来说,我建议不要为受保护的控制器方法编写测试,它们应该由调用它们的任何面向公众的方法来执行。

      在你的情况下,只要你测试任何调用源,你就会测试源。

      如果你真的需要,尽管你可以做到;

      @controller = MyController.new
      @controller.send(:source) #this will call source
      

      【讨论】:

      • :- 感谢您的回答,但我收到错误 undefined_method to_sym for nil:NilClass
      • 我想您将 MyController 更改为您的控制器的名称?您能否更新您的问题以显示您正在尝试的代码?
      【解决方案3】:

      我修好了。问题是第一个测试中的返回字符串和第二个测试中的对象。这是我要解决的问题。

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多