Skip to content

What's the best way of getting DB connection in tests? #1776

Answered by bubelov
bubelov asked this question in Questions
Discussion options

You must be logged in to vote

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:

#[test]
fn exchange_rates_controller_get() {
    let (client, mut db) = setup();

    let rate = ExchangeRate {
        base: "USD".to_string(),
        quote: "…

Replies: 2 comments 7 replies

Comment options

You must be logged in to vote
7 replies
@jebrosen
Comment options

@bubelov
Comment options

@jebrosen
Comment options

@SergioBenitez
Comment options

@bubelov
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by bubelov
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
3 participants