在轨道排序迷你测试

问题描述:

我是新来的铁轨,我做了一个简单的日期降序排序。现在我需要为它写一个测试。我的控制器看起来像这样在轨道排序迷你测试

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 
+0

请问您能否具体说明一下。 –

+0

我想写一个测试排序的记录 –

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

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

你的情况,你没有创建一个“排序”,您创建了一个controlleraction,查询按降序排列记录,所以要么测试你需要一个控制器测试或一个集成测试(控制器测试我认为正在放弃使用而不是集成测试),因为您需要访问测试路径,然后断言您的结果与预期一致。

我认为最好的办法是实际为您的模型创建一个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 

而你也需要两场比赛至少有不同的日期,但我会建议你在articles.yml文件中有4或5个不同的日期并以不同的顺序写入(以确保测试通过,因为它是正确的,而不仅仅是因为随机性),并将您的index操作更改为:

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

(如果你有,你查询文章的其他地方,你需要他们以另一种方式排序,而不是default_scope,创建一个特定的一种,使用,无论是在控制器和模型试验)

+0

嘿! Micael非常感谢你为我工作:D –

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

我假设你的控制器被命名为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指南中的更多信息。