简体   繁体   English

如何在Rails中编写控制器测试

[英]how to write controller test in Rails

I'm really not sure how to write a controller test. 我真的不确定如何编写控制器测试。

Given is one of the controller action. 给定是控制器动作之一。

  class AccountsController < ApplicationController
    def pstn_rate_imports
        page = params[:page] || 1
        @pstn_rate_imports = @resporg_account_id.pstn_rate_imports.order('created_at desc').page(page).per(10)
        @pstn_rate_import = PstnRateImport.new
      end
   end

Now I approach this in 2 way.. 现在,我以两种方式处理此问题。

  1. I can insert data on PSTN Rate import table and then test that. 我可以在PSTN Rate导入表上插入数据,然后进行测试。 and then write a test which probably will verify whether the returned object exactly matches to test result expectation. 然后编写一个测试,该测试可能会验证返回的对象是否与测试结果期望完全匹配。

Like, 喜欢,

get :pstn_rate_imports, id: 1, page: 1
expect(assigns(:pstn_rates_imports)).to eq(expected_result)

but here a problem, I would now need to sure of that I insert a correct data on DB (worry about validation etc, etc when creating records) Also, this does not adhere to the principle that any new chance you introduce should break your test. 但是这里有一个问题,我现在需要确保我在数据库上插入了正确的数据(担心在创建记录时会进行验证等问题)。此外,这并不符合您引入的任何新机会都会破坏测试的原则。

  1. OR I can mock the ActiveRecord call. 或者,我可以模拟ActiveRecord调用。

expect_any_instance_of(ResporgAccountId).to receive(:pstn_rate_imports) { some_arel } Expect_any_instance_of(ResporgAccountId).to接收(:pstn_rate_imports){some_arel}

expect(some_arel).to receive(:order).with('created_at desc') { some_arel } 期望(some_arel)。接收(:order).with('created_at desc'){some_arel}

expect(some_arel).to receive(:page).with('1') { some_arel } 期望(some_arel)。接收(:page).with('1'){some_arel}

expect(some_arel).to receive(:per).with(10) { some_arel } 期望(some_arel)。接收(:per).with(10){some_arel}

get :pstn_rate_imports, id: 1, page: 1 得到:pstn_rate_imports,id:1,页面:1

This ensures that if I change anything the test would fail. 这样可以确保如果我进行任何更改,测试都将失败。 But the problem is that I'm not sure how to mock the arel object or ActiveRecord method that returns an arel object . 但是问题是我不确定如何mock the arel object or ActiveRecord method that returns an arel object

So what is the correct way to write controller test in Rails. 那么在Rails中编写控制器测试的正确方法是什么。

The main principle is writing a test that covers the tested object functionality only. 主要原理是编写仅涵盖测试对象功能的测试。

So you need to: 因此,您需要:

  • test the logic ( pstn_rate_imports method) creating a relative test for the model method 测试逻辑( pstn_rate_imports方法),为模型方法创建相对测试
  • test variables assigning and controller's specific logic (like .order ) in the controller. 测试变量的分配以及控制器中控制器的特定逻辑(例如.order )。 Model's methods (like pstn_rate_imports ) should be stubbed for sure. 应该确保对模型的方法(如pstn_rate_imports )进行存根处理。 You can read more about the stubbing here . 您可以在此处阅读有关存根的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM