代码之家  ›  专栏  ›  技术社区  ›  Rachel Dias

rails中的排序迷你测试

  •  0
  • Rachel Dias  · 技术社区  · 7 年前

    我是rails新手,我已经按降序对日期进行了简单排序。现在我需要为它编写一个测试。我的控制器看起来像这样

    def index
      @article = Article.all.order('date DESC')
    end
    

    我试着写一个测试,但它不工作,这是我的代码

    def setup
      @article1 = articles(:one)
    end
    
    test "array should be sorted desc" do
      sorted_array = article1.sort.reverse
      assert_equal article1, sorted_array, "Array sorted"
    end
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   m3characters    7 年前

    你应该写一个更好的描述,说代码的每一部分都指什么,比如:

    # this is my controller_whatever.rb
    def index
     @article = Article.all.order('date DESC')
    end
    
    #this is my test/controllers/controller_whatever_test.rb
    
    def setup
      @article1 = articles(:one)
    end
    ...
    

    在您的情况下,您没有创建“排序”,而是创建了一个 controller action 它按降序查询记录,因此要测试它,您需要控制器测试或集成测试(我认为控制器测试正在被放弃,以支持集成测试),这更复杂,因为您需要访问测试中的路径,然后断言您的结果与预期相符。

    我认为最好的方法是创建一个 scope index

    这类似于:

    # app/models/article.rb
    scope :default -> { order(date: :desc) }
    

    #test/models/article_test.rb
    
    def setup
      @articles = Article.all
    end
    
    test "should be most recently published first" do
      assert_equal articles(:last), @articles.first
      assert_equal articles(:first), @articles.last
    end
    

    你至少需要两个不同日期的固定装置,但我建议你有4个或5个不同日期的固定装置,并在文章中以不同的顺序书写。yml文件(确保测试通过,因为它是正确的,而不仅仅是因为随机性),并更改 指数 操作简单:

    def index
      @article = Article.all # since now you have a default_scope
    end
    

        2
  •  0
  •   guitarman    7 年前

    我会根据索引操作的控制器在测试类中编写一个功能测试。

    我想你的控制器的名字是 ArticlesController ArticlesControllerTest 放置在 test/controllers/articles_controller_test.rb .

    在测试方法中,您调用/请求控制器的索引操作,并首先检查是否有成功的答案。然后捕捉文章,控制器在 @article1 assigns(:article1) .

    class ArticlesControllerTest < ActionController::TestCase
      test "index should provide sorted articles" do
        get :index
        assert_response :success
    
        articles = assigns(:article1)
        assert_not_nil articles
    
        date = nil
        articles.each do |article|
          if date
            assert date >= article.date
          end
    
          date = article.date
        end
      end
    end
    

    了解 Functional Tests for Your Controllers 详见Rails 4.2指南。