2đź‘Ť
These two approaches are testing different things:
-
Your test case tests the model layer — it asks the question “if I create a user and save it, does the profile record get created automatically?”
It doesn’t depend on how the user object was created — Through an admin view, or a user signup view, or a management command — as long as this test passes, you know that any method of creating a user through the ORM will add a profile.
It also doesn’t care how the profile is created. It could be through a pre-save signal, a post-save signal, some code in an overridden save() method, or magic. As long as the record is created, the test will pass.
-
The code you found in django-registration is testing the view layer. It is calling a specific view function,
register
, passing it three URL parameters, and asking the question “did theuser_registered
signal get fired as a result of this view?”This test case doesn’t look at other methods of creating a user; just the registration view. It’s not concerned with any other methods of creating a user.
It also doesn’t look at whether a profile was created. All it wants to know is that the signal was fired, regardless of what that signal actually does in any particular application.
What’s the difference?
Your code is a great example of an integration test — “Did I put all of these parts (models, signals) together in right order so that profiles get created?” — and of a regression test, to signal you in the future whether you’ve done anything that has broken the user profile creation.
The django-registration code is an actual unit test. It very carefully isolates just the view code, to call it in a controlled environment and ask one simple question of it.
Which is better?
In your case, you probably don’t need to write the unit test. (Though there could be a lot of debate about that; it’s practically a matter of religion in some parts) You want a way to verify that the code that pieces that you’ve put together are working as you expect them to, and your test is the best way to do that.
Don’t worry about actually creating a user — during the test run, you’re doing everything in a transaction, and that transaction is rolled back immediately after the test method completes. It may not even hit the disk. And, as @Platinum Azure mentioned, it’s all on a test database anyway.
0đź‘Ť
Why do you want to mock out the user creation? You’re testing against a test database if you run Django’s test engine. Just call the view or use a request client factory and let the test runner drop the test database when it’s done.
- [Answered ]-Hidden form field using none model forms
- [Answered ]-How can I get data from two ForeignKey fields in TastyPie?
- [Answered ]-Django complicated queryset