简体   繁体   中英

How can I test arbitrary routes in Rails?

I'd like to write a Rails functional test for a non-RESTful route.

I'm using Test::Unit.

In routes.rb I have this route...

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

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.

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.

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) is nil and so when you call length on it it returns a NoMethodError .

The answer must be in your contract_search action, can you post the code?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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