Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 5ddf984

Browse files
committedMar 18, 2025··
docs: testing auth routes
1 parent 2e66056 commit 5ddf984

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
 

‎docs-site/content/docs/extras/authentication.md

+67
Original file line numberDiff line numberDiff line change
@@ -255,3 +255,70 @@ curl --location '127.0.0.1:5150/api/user/current-api' \
255255
```
256256

257257
If the `API_KEY` is valid, you will get the response with the user details.
258+
259+
# Testing
260+
The following example works for both JWT and API_KEY Authentication.
261+
```rust
262+
// tests/requests/example.rs
263+
use loco_rs::testing::prelude::*;
264+
use crate::requests::prepare_data;
265+
266+
#[tokio::test]
267+
#[serial]
268+
async fn can_get_current_user() {
269+
configure_insta!();
270+
271+
request::<App, _, _>(|request, ctx| async move {
272+
// Initialize the user
273+
let user = prepare_data::init_user_login(&request, &ctx).await;
274+
let (auth_key, auth_value) = prepare_data::auth_header(&user.token);
275+
276+
// Then add the key to the request, usually in the header
277+
let response = request
278+
.get("/example")
279+
.add_header(auth_key, auth_value)
280+
.await;
281+
282+
assert_eq!(
283+
response.status_code(),
284+
200,
285+
"Current request should succeed"
286+
);
287+
288+
// Shapshot
289+
assert_debug_snapshot!((response.status_code(), response.text()));
290+
})
291+
.await;
292+
}
293+
```
294+
295+
For a post requests, add a payload:
296+
``` diff
297+
let response = request
298+
- .get("/example")
299+
+ .post("/example")
300+
.add_header(auth_key, auth_value)
301+
+ .json(&serde_json::json!({"site": "Loco"}))
302+
.await;
303+
```
304+
305+
## Async Tests
306+
Instead of using request, as described in the documentation for synchronous tests, use the request_with_create_db function.
307+
```diff
308+
// tests/requests/example.rs
309+
use loco_rs::testing::prelude::*;
310+
use crate::requests::prepare_data;
311+
312+
#[tokio::test]
313+
- #[serial]
314+
async fn can_get_current_user() {
315+
configure_insta!();
316+
317+
- request::<App, _, _>(|request, ctx| async move {
318+
+ request_with_create_db::<App, _, _>(|request, ctx| async move {
319+
// Initialize the user
320+
// ...
321+
})
322+
.await;
323+
}
324+
```

0 commit comments

Comments
 (0)
Please sign in to comment.