简体   繁体   English

如何在Rails中测试任意路由?

[英]How can I test arbitrary routes in Rails?

I'd like to write a Rails functional test for a non-RESTful route. 我想为非RESTful路由编写Rails功能测试。

I'm using Test::Unit. 我正在使用Test :: Unit。

In routes.rb I have this route... routes.rb我有这条路线......

match '/contract_search' => 'contracts#contract_search', \
    :as => 'contract_search', \
    :via => :post

And in my Contracts controller I have this action... 在我的合约控制器中我有这个动作......

def contract_search
  # ...
end

In contracts_controller_test.rb I tried... contracts_controller_test.rb我试过......

test 'POST to contracts with search params.' do
  post(:contract_search, {
    :contract_search => {
      :title_like => 'System'
    }
  }, unprivileged_internal_user_session_vars, { })

  assert(
    assigns(:contracts).length == 6,
    "@contracts.length #{assigns(:contracts).length} is incorrect."
  )

end

The action works as expected in the browser. 该操作在浏览器中按预期工作。

But the test just errors out with... 但测试只是错误...

  1) Error:
test_POST_to_contracts_with_search_params.(ContractsControllerTest):
NoMethodError: undefined method `length' for nil:NilClass
    test/functional/contracts_controller_test.rb:49:in `block in <class:ContractsControllerTest>'

My sense is that the Test::Unit is trying to post to /contracts/contract_search , I think. 我的感觉是Test :: Unit试图发布到/contracts/contract_search ,我想。

What is the correct way to do this? 这样做的正确方法是什么?

Since in your test code you are using assigns(:contracts) , You must make sure that your controller method is populating the @contracts variable properly. 因为在您的测试代码中您使用的是@contracts assigns(:contracts) ,所以您必须确保控制器方法正确填充@contracts变量。

May be you have missed some prerequisite to run the test case. 可能是你错过了运行测试用例的一些先决条件。

The problem is not with routing, it's with the assigns(:contracts) in your assertion. 问题不在于路由,而是在断言中assigns(:contracts) assigns(:contracts) is nil and so when you call length on it it returns a NoMethodError . NoMethodError assigns(:contracts)为nil,因此当你调用length ,它会返回NoMethodError

The answer must be in your contract_search action, can you post the code? 答案必须在您的contract_search操作中,您可以发布代码吗?

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

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