Feature specs for exceptional scenarios - ruby-on-rails

I read that controller specs are going out of favor and that the current recommendation is to use feature and request specs. I've found feature specs have been working really well for happy path testing, but I'm having some difficulty with exceptional cases I want to test. For instance I have an index of resources owned by a user. This list includes buttons to destroy each resource. Users only see their own resources. I want to add a test that attempting to destroy one that belongs to someone else fails. The problem is that the list won't include anybody else's items so there isn't an appropriate link to tell capybara to click. In a controller test I could directly issue a DELETE on the resource's path, but as best I can tell that is not an option in feature specs. Am I missing something? Do I need to implement request specs too if I want coverage outside the happy path? I was hoping to reserve request specs for covering my API endpoints.

From my point of view, permission specs should NOT be implemented as feature specs. Your thoughts fully makes sense and the only one thing you can really check there is that you DON'T see any entities, that were made by other users. Your logical difficulties is like +1 point, that such scenarios should be tested via another spec types. Also... feature specs are expensive and I would never do such 'deep' test in features.

Related

Rails and Testing, why testing controllers is not enough?

I was wondering, as testing a controller in rails run the associated views (even if not shown) and integrate many models concerns (by saving, updating,...), testing controller should be almost enough for all applications near enough of CRUD classical architecture. Am I wrong?
Furthermore, views can be tested in the browser, as eyes can be quicker to check than describing everything in a test (and they can achieve CSS control too.)
Thank you for your point of view!
PH
Testing only your controllers will tell you that, broadly, your app is working, at least in terms of not 500'ing or whatever. But can you be sure that it is doing the exactly correct thing? If all you need to test is standard resourceful behaviour like "given params[:id], is the record with id <params[:id]> loaded?" then just testing the controller might be enough.
But, you will inevitably add more complicated behaviour into your models. In this situation, your controller may set some variables or something, without raising an error, by calling a model method. At this stage, it's much cleaner to test the model method directly, to make sure that given a particular set of conditions, it does the right thing.

Structure of BDD tests

I'm digging into Capybara and rspec, to move from TDD to BDD.
My generators make a whole lot of directories and spec tests,
with directory structure similar to this:
spec
controllers
models
requests
routing
views
I think that most of this is TDD rather than BDD. If I read here:
"A great testing strategy is to extensively cover the data layer with
unit tests then skip all the way up to acceptance tests. This approach
gives great code coverage and builds a test suite that can flex with a
changing codebase."
Then I figure that things should be quite different
something on the lines of:
spec
models
acceptance
Basically I take out controllers, requests, views, and routing to just implement tests as user case scenarios in the acceptance directory with Capybara, Rspec.
This makes sense to me, though I'm not sure if this is the standard/common approach to this.
What is your approach?
Thanks,
Giulio
tl;dr
This is not a standard approach.
If you only test models and feature specs... then you miss out on the bits in the middle.
You can tell: "method X broke on the Widget model" or you can tell "there's something wrong while creating widgets" but you have no knowledge of anything else.
If something broke, was it the controller? the routing? some hand-over between the two?
it's good to have:
extremely thorough testing at the model-level (eg check every validation, every method, every option based on incoming arguments)
rough testing in the middle to make sure sub-systems work the way you expect (eg controllers set up the right variables and call the right templates/redirections given a certain set of circumstances)
overall feature testing as smoke-tests (eg that a user can go through the happy path and everything works the way they expect... that if they input bad stuff, that the app is throwing up the right error messages and redisplaying the forms for them to fix the problem)
Don't forget that models aren't the only classes in your app.. and all classes need some kind of testing. Controllers are classes too. As are form and service objects, mailers, etc.
That said - it's common to consider that view-tests are going overboard. I'm also not keen on request-tests our routing test myself (unless I have something complex which I want to work right, eg lots of optional params in a route that map to interesting search-patterns)

Best way to further secure rails app from?

I am using rails 3.2 and devise 1.5.3.
I added an admin attribute in my model as described in option 2 on the devise wiki How To: Add an Admin Role
I added this in a post controller for force logins:
before_filter :authenticate_user!
I wrote some logic to hide the edit/new links in my views based on whether you're an admin or not.
I feel like there's more I should be doing.. Should I add anything else to new/edit/delete actions to make them more secure? If so, where?
your answer may be working but it is pretty difficult to ensure security in the whole app if you are using some logic to hide the edit/new links in my views and I'm pretty sure no amount of security testing would give you the feeling that maybe you are forgetting about something
for example I someone could log in,,,, (not having admin profile) and go to (in the URL),:
/users/edit/3 and start damaging your valuable information....
situation is: Devise only provides authentication,,, but authorization has to be enforced in some other way or else I could be able to do the above things...
for that I would highly recommend CanCan (from rbates ofcourse) which is the one I have tested personally and is PRETTY easy to configure just by reading the docs and examples in github..... hope it helps!
Your authentication and authorization mechanism is in charge of taking care of security for you, and you should make sure it's regularly updated with security updates.
That sinking feeling that you have about missing something can only reliably be covered by tests. So, write some tests that verify that the way you've setup your Devise installation is, in fact, correct, and they non-admin users do not have access to anything they shouldn't have access to. Then be very careful to make sure you update your security restrictions as you add new things.
You don't need to write tests to make sure Devise works - but you do need to write tests to make sure that your use of it is what you think it is (i.e. if non-admins shouldn't be able to get to the admin page, write a test that logs in as a non-admin, try to access that page, and verify in the test that the user is redirected and, if you have an 'access denied' message, that's it's firing). That way, if you inadvertently break security access later, you at least stand a chance that it'll be caught by a test in your test suite.
Run your test suite before every deploy, making sure that all tests (especially security tests) are running and passing. Then be vigilant thereafter, and that's about all you can do.

What's a proper way of writing request specs in RSpec?

tl;dr: Jump to the last paragraph
Recently I've been trying to use RSpec's request specs to do some more targeted testing.
This is how my testing mostly looks:
general cucumber feature specification, i.e. user goes to a post with comment, upvotes on a comment and the author gets points
model specs for when the model actually has some functinality, i.e. User#upvote(comment)
controller specs where I stub most of the things and just try to make sure the code goes the way I expect
view specs for when there is something complex in the view, such as rendering a upvote link only when the user didn't already upvote, and these are stubbed as well
The problem is when I have some specific scenario which causes a bug and everything seems to work in the model/view layer where I am unable to reproduce it.
That forces me to write an integration test, which I can also do in cucumber. The problem arises once I am able to actually reproduce it, and I need to figure out why is it happening. This usually means playing around in tests, changing different things and seeing what happens.
For example create a comment that is owned by the user who is trying to upvote, try to vote with an expired session etc. However these are really huge pain to write in Cucumber, because of the need to write a scenario and then specify each step.
At this point, I prefer to write a request spec, because it is more low level and allows me to directly do stuff. The problem is, that I'm not really sure how to properly write a request spec, or what are the rules.
A simple example here is:
visit login_path
fill_in "Username", :with => user.username
fill_in "Password", :with => user.password
click_button "Log in"
vs
post sessions_path(:username => user.username, :password => user.password)
or even something more low level like
session[:user_id] = user.id # this actually doesn't work, but the idea is there
Both of these examples achieve the same thing, they'll log a user in. I know that the answer to which one to pick is based on what I need to test, but that doesn't answer the correct, conventional way to do this.
I've been trying to find something about request specs, but they're not really described anywhere. The RSpec book doesn't cover them, the RSpec documentation doesn't say anything either.
What is a correct way to write request specs? When should I use capybara and when just the Rails' #get and #post methods instead of clicking buttons and visiting paths?
For requests spec I believe the convention is to stick to testing user behaviour and interface interactions, which would mean loading the page, filling in the form etc. A website user cant set the session or interact with variables directly so neither should your request specs.
I've often been tempted to skip page loads and form interactions by posting or setting variables in request specs (for speeds sake, especially heavy ajax specs) but it really does break the purpose of a request spec.
As the comments mentioned, you should test the specific controller / view behaviour in the other spec types.
Sermon first....
I think the natural progression of YOU the test writer goes:
Controller
Model
Requests
a mix of Request, Controller and Model specs.
I know that I started looking at the controller first, cause it was easier to grasp.
You then get into Model specs, for non-happy path things...
Then you realize rspec doesn't actually render the view, so you are starting to see dumb errors in Airbrake, so you say, shoot... I need to test the views, and the workflow. Hence Request specs.
Lastly, you get older and realize, all 3 are important and should be used sparingly, but accordingly. I'm just at step 4 now... too many request specs, and you are slogging 5 mins for the whole suite on a medium sized app. sucks.
To answer your question:
I test workflow and views i need to be "seen" (with page.should or any tricky JS (jquery ui selectors for instance) with capybara in a request spec.
If i just need to make sure the controller variables are instantiated or to do something quick with a post for a non-happy path , out of workflow thing... I use the controller. E.g., POST to IPN Controller in paypal...
You'd be surprised how much this covers. This leaves you to test the models for all the whacked out stuff you need for total all the edge cases.
Honestly though, I'd say use Fixtures and Test Unit for integration tests... still like them better, faster... stronger... etc.

Should I really test controllers?

I'm trying to get the best codecoverage/development time result
Currently I use rspec+shoulda to test my models and rspec+capybara to write my acceptance tests.
I tried writing a controller test for a simple crud but it kinda took too long and I got a confusing test in the end(my bad probably)
What`s the best pratice on controller testing with rspec?
Here is a gist on my test and my controller(one test does not pass yet):
https://gist.github.com/991687
https://gist.github.com/991685
Maybe not.
Sure you can write tests for your controller. It might help write better controllers. But if the logic in your controllers is simple, as it should be, then your controller tests are not where the battle is won.
Personally I prefer well-tested models and a thorough set of integration (acceptance) tests over controller tests any time.
That said, if you have trouble writing tests for controllers, then by all means do test them. At least until you get the hang of it. Then decide whether you want to continue or not. Same goes for every kind of test: try it until you understand it, decide afterwards.
The way I view this is that acceptance tests (i.e. Cucumber / Capybara), test the interactions that a user would normally perform on the application. This usually includes things like can a user create a specific resource with valid data and then do they see errors if they enter invalid data. A controller test is more for things that a user shouldn't be able to normally do or extreme edge cases that would be too (cu)cumbersome to test with Cucumber.
Usually when people write controller tests, they are effectively testing the same thing. The only reason to test a controller's method in a controller test are for edge cases.
Edge cases such as if a user enters an invalid ID to a show page they should be shown a 404 page. This is a very simple kind of thing to test with a controller test, and I would recommend doing that. You want to make sure that when they hit the action that they receive a 404 response, boom, simple.
Making sure that your new action responds successfully and doesn't syntax error? Please. That's what your Cucumber features would tell you. If the action suddenly develops a Case of the Whoops, your feature will break and then you will fix that.
Another way of thinking about it is do you want to test a specific action responds in a certain way (i.e. controller tests), or do you care more about that a user can go to that new action and actually go through the whole motions of creating that resource (i.e. acceptance tests)?
Writing controller tests gives your application permission to lie to you. Some reasons:
controller tests are not executed in the environment they are run in. i.e. they are not at the end of a rack middleware stack, so things like users are not available when using devise (as a single, simple example). As Rails moves more to a rack based setup, more rack middlewares are used, and your environment deviates increasingly from the 'unit' behaviour.
You're not testing the behaviour of your application, you're testing the implementation. By mocking and stubbing your way through, you're re-implementing implementation in spec form. One easy way to tell if you're doing this; if you don't change the expected behaviour of url response, but do change the implementation of the controller (maybe even map to a different controller), do your tests break? If they do, you're testing implementation not behaviour. You're also setting your self up to be lied to. When you stub and mock, there's no assurances that the mocks or stubs you've setup do what you think they do, or even if the methods they're pretending to be exists after refactoring occurs.
Calling controller methods is impossible via your applications 'public' api. The only way to get to a controller is via the stack, and the route. If you can't break it from a request via a url, is it really broken?
I use my tests as an assurance the my application is not going to break when I deploy it. Controller tests add nothing to my confidence that my application is indeed functional, and actually their presence decreases my confidence.
One other example, when testing your 'behaviour' of your application, do you care that a particular file template was rendered, or that a certain exception was raised, or instead is the behaviour of your application to return some stuff to the client with a particular status code?
Testing controllers (or views) increases the burden of tests that you impose on yourself, and means that the cost of refactoring is higher than it needs to be because of the potential to break tests.
Should you test? yes
There are gems that make testing controllers faster
http://blog.carbonfive.com/2010/12/10/speedy-test-iterations-for-rails-3-with-spork-and-guard/
Definitely test the controller. A few painfully learned rules of thumb:
mock out model objects
stub model object methods that your controller action uses
sacrifice lots of chickens.
I like to have a test on every controller method at least just to eliminate stupid syntax errors that may cause the page to blow up.
A lot of people seem to be moving towards the approach of using Cucumber for integration testing in place of writing controller and routing tests.

Resources