简体   繁体   中英

Spec for testing a controller method that calls model methods

I'm refactoring my controllers to by moving the logic to the model. I was finding it hard to test my controller methods when they had so much logic (also was not able to reuse logic in controllers). Now I'd like to understand how to write specs for these controllers. I'm following this testing guide .

Here's an example:

def dashboard
  @sorted_deals = Deal.deals_for_user(current_user)
end

This calls a class method that has some logic that finds the relevant deals and sorts them appropriately. It feels like unessary duplication to test deals_for_user again (I already test it in my Model spec). How do I test this method without needless duplication? Is this a case to use mocks or stubs?

There is some debate on the usefulness of controller tests in Rails. Personally I unit test the shit out of my models and the only real tests that I do for controllers are integration testing using a headless browser such as Selenium with capybara. If you know your method works and is tested, and the view/associated logic works and is tested through integration tests, controller testing is almost a waste of time. There are other opinions on this and I am in no way a guru but I thought I would put in my $00.02.

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