在 rails 中排序迷你测试

sort mini test in rails

我是 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

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

# 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
...

在你的例子中你没有创建一个 "sorting",你创建了一个 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 个不同日期并以不同顺序写入 articles.yml 文件(以确保测试通过是因为它是正确的,而不仅仅是因为随机性),并将您的 index 操作简单地更改为:

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

(如果您在其他地方查询文章并且需要以另一种方式而不是 default_scope 对它们进行排序,请创建一个特定的文章并在控制器和模型测试中使用它)

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

我假设你的控制器被命名为 ArticlesController 然后测试 class 名称是 ArticlesControllerTest 放置在 test/controllers/articles_controller_test.rb.

在测试方法中,您 call/request 控制器的索引操作并首先检查是否成功。然后你用 assigns(:article1)@article1 实例变量中捕获你的控制器 returns 的文章。

现在您可以检查您的文章是否已设置,您可以检查日期。在这里,我以一种简单的方式遍历所有文章,并比较之前文章的日期是否大于或等于当前文章的日期,因为降序排列。对于一个简单的测试来说应该是可以接受的,因为你不应该有大量的测试记录。可能有更好的方法来检查订单。

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

阅读 Rails 4.2 指南中的 Functional Tests for Your Controllers 了解更多信息。