【问题标题】:How do you test code that is not a model or controller你如何测试不是模型或控制器的代码
【发布时间】:2009-03-06 23:09:48
【问题描述】:

我在 Rails 项目的 lib 目录的文件中定义了一个类,它将实现一堆实用程序函数作为类方法。我想使用 Test::Unit 针对这些方法编写测试,并将它们作为项目常规测试例程的一部分运行。

我尝试将文件粘贴到 test 目录的顶层...

require 'test_helper'

class UtilsTest < ActiveSupport::TestCase
  should 'be true' do
    assert false
  end
end

...但这没有用。测试没有运行。

测试不是 Rails 常规部分之一的代码的正常方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby unit-testing testing


    【解决方案1】:

    我只是把它们放在测试/单元中。我不确定这是否是“正确”的方法,但它似乎对我有用......

    【讨论】:

      【解决方案2】:

      您可以将它们放在您的单位目录中,而不会有任何复杂性。

      我的图书馆:

      [ cpm juno ~/apps/feedback ] cat lib/my_library.rb
      class MyLib
        def look_at_me
          puts "I DO WEIRD STUFF"
        end
      end
      

      我的测试:

      [ cpm juno ~/apps/feedback ] cat test/unit/fake_test.rb
      require 'test_helper'
      
      class FakeTest < ActiveSupport::TestCase
        # Replace this with your real tests.
        def test_truth
          require 'my_library'
      
          puts "RUNNING THIS NOW"
          MyLib.new.look_at_me
          assert true
        end
      end
      

      并运行它:

      [ cpm juno ~/apps/feedback ] rake test:units
      (in /home/cpm/apps/feedback)
      /usr/bin/ruby1.8 -Ilib:test "/usr/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/unit/fake_test.rb"
      Loaded suite /usr/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
      Started
      RUNNING THIS NOW
      I DO WEIRD STUFF
      .
      Finished in 0.254404 seconds.
      
      1 tests, 1 assertions, 0 failures, 0 errors
      Loaded suite /var/lib/gems/1.8/bin/rake
      Started
      
      Finished in 0.00094 seconds.
      
      0 tests, 0 assertions, 0 failures, 0 errors
      

      只要它以 _test.rb 结尾,它就应该把它捡起来。

      【讨论】:

        【解决方案3】:

        这是测试助手功能的 test\functional\application_helper_test.rb 示例

        require File.dirname(__FILE__) + '/../test_helper'
        
        require 'application_helper'
        
        class HelperTest < Test::Unit::TestCase
            include ApplicationHelper
        
            def test_clear_search_string
                assert_equal 'Park Ave', clear_search_string('street Park Ave')
            end
        end
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-01-06
          • 1970-01-01
          • 2010-10-31
          相关资源
          最近更新 更多