I am using RoR4, Cancan(1.5.0) and Devise(3.2.2). I am using Test:Unit to test my application. The problem is that if I separate the requests in different functions, it works, but if inside a function I perform two tests, it seems like it evaluates the response of the first request, even after subsequent requests: This works:
test 'admin cannot delete product that has line_items associated' do
sign_in @admin_user
assert_no_difference('Product.count') do
delete :destroy, id: @prod_to_all
end
assert_redirected_to product_path(@prod_to_all)
end
test 'admin can delete product that has no line_items associated' do
sign_in @admin_user
assert_difference('Product.count', -1) do
delete :destroy, id: products(:prod_to_all_not_ordered)
end
assert_redirected_to products_path
end
If I put them requests together, it fails:
test 'admin cannot delete product that has line_items associated, but can delete one that has no line_items associated' do
sign_in @admin_user
assert_no_difference('Product.count') do
delete :destroy, id: @prod_to_all
end
assert_redirected_to product_path(@prod_to_all)
assert_difference('Product.count', -1) do
delete :destroy, id: products(:prod_to_all_not_ordered)
end
assert_redirected_to products_path
end
Error:
"Product.count" didn't change by -1.
Expected: 5
Actual: 6
My issue is that I have 3 roles: public_user, client, and admin. And to test every function for each role in different functions is a pain. even for simple controllers, it gets bigger than it should, and I hate that solution.
What do you guys suggest? Do I really need to embrace rspec and its contexts or can I get away with test:unit and keep the code DRY?
Besides, it seems to me that something is not so well with test:unit, due to the fact that it doesn't evaluate the second request correctly...is it a bug or something more structural that I am not understanding?
Thank you
I actually like the separate version better. It is cleaner. And I personally like my tests to not be too dry. It makes them more verbose. Which I prefer: Duplication in Tests Is Sometimes good
Rails functional tests are meant to be run with one request per test. If you want to tests multiple requests you can use an integration tests. It is hard to tell the error without seeing the controller code. It might be that you application is loosing the logged in user during requests. Or that they share state (e.g. instance variables). Debug with pry or some alternate debugger or just plain old puts to see the state of objects.