Rust初心者が勉強したことを記録する備忘録。
今日やった事
参考ページ
単体テストを書く
Rustではテストコードを同じファイル内に書く文化らしい。
まずは、 src/models/post.rs にDBに関係しないところを試しに書いてみた。
#[cfg(test)] mod tests { use super::*; #[test] fn unit_sample() { let post = Post { id: 1, title: "title".to_string(), body: "body".to_string(), published: false, }; assert_eq!(post.id, 1); assert_eq!(post.title, "title"); assert_eq!(post.body, "body"); assert_eq!(post.published, false); } }
DB周りはテスト実行後にロールバックとかする必要あるので、また別の日に挑戦したい。
結合テストを書く
tests/main.rs を作成し、HTTPリクエストを投げて、 200 OK
などを確認する最低限のテストを書いた。
#[cfg(test)] mod tests { extern crate rust_web; use actix_web::dev::Service; use actix_web::http::StatusCode; use actix_web::{test, App}; use bytes::Bytes; use rust_web::routes; #[test] fn get_root() { let mut app = test::init_service(App::new().configure(routes::top).configure(routes::posts)); let req = test::TestRequest::get().uri("/").to_request(); let resp = test::block_on(app.call(req)).unwrap(); assert_eq!(resp.status(), StatusCode::OK); assert_eq!(test::read_body(resp), Bytes::from_static(b"Hello world!")); } #[test] fn post_posts() { let mut app = test::init_service(App::new().configure(routes::top).configure(routes::posts)); let req = test::TestRequest::post().uri("/posts").to_request(); let resp = test::block_on(app.call(req)).unwrap(); assert_eq!(resp.status(), StatusCode::CREATED); assert_eq!(test::read_body(resp), Bytes::from_static(b"Inserting")); } }
CircleCIを設定する
テストコードを書いたのでCircleCIの設定もしておいた。
version: 2.1 jobs: build: docker: - image: circleci/rust environment: DATABASE_URL: test.sqlite3 steps: - checkout - run: cargo fmt -- --check - run: cargo install diesel_cli - run: diesel setup - run: cargo test