-
I'm working on a simple API as an exercise in Rust and Rocket, and I have some issues with figuring out the best way to test my endpoints. Here is my setup and intentions:
Nothing fancy, just the usual test workflow. Here are my problems so far:
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 7 replies
-
See the
That's the best approach. See the
Do you mean Rust's
Where did you get the idea that only two profiles are supported? Have you read through the configuration guide? You can have any number of profiles with any name. |
Beta Was this translation helpful? Give feedback.
-
Answering my own question: The cleanest way of getting a DB connection is to do it directly, before even touching Rocket. Getting a database via Rocket involves async code and anonymous functions, which complicates things quite a bit for no good reason. It's better to connect to your DB directly via the base crate under your DB pool (e.g. Here is an example: #[test]
fn exchange_rates_controller_get() {
let (client, mut db) = setup();
let rate = ExchangeRate {
base: "USD".to_string(),
quote: "EUR".to_string(),
rate: 1.25,
};
exchange_rates::insert(&mut db, &rate);
let res = client.get("/exchange_rates?base=USD"e=EUR").dispatch();
assert_eq!(res.status(), Status::Ok);
let body = res.into_json::<ExchangeRate>().unwrap();
assert_eq!(rate, body);
} PS. Beware that it's also desirable to clean the DB after every test somehow, so they won't interfere with each other. I'm not sure what's the best way of doing that. Simply dropping the DB after each test won't work either, because cargo is very pushy on executing tests in parallel. I'm yet to find a satisfying way of making all tests run in sequence. Passing the number of threads on every cargo test invocation is a deal breaker. There are some crates which force serial execution via per-test annotations but it adds a lot of boilerplate. An alternative option would be to generate an unique in-memory database per test, which may be the best option for SQLite, but I didn't try it yet (added: tried it, works like a charm, so there is no need to worry about concurrency and cleaning the database, it gets cleaned up automatically). |
Beta Was this translation helpful? Give feedback.
Answering my own question:
The cleanest way of getting a DB connection is to do it directly, before even touching Rocket. Getting a database via Rocket involves async code and anonymous functions, which complicates things quite a bit for no good reason. It's better to connect to your DB directly via the base crate under your DB pool (e.g.
rusqlite
), and then let Rocket do what it usually does with no extra tweaks. That way, tests can keep using blocking API and avoid anonymous functions and their side effects.Here is an example: