Note: This project is currently in a work in progress so not all languages or sections are complete.

Test Driven Development with Rust

Installing Homebrew

We're going to start by installing Homebrew which will make installing everything else we need much easier.

Open a Terminal window and run the following commands:

1
2
xcode-select --install
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Installing Rust

Now we can easily install Rust with Homebrew using the following:

1
brew install rust

Creating the Project

Now we'll use Cargo to initialize a project for us.

1
2
3
# cargo is installed along with Rust
cargo new ustray --lib
cd urstray

Dependency Management

When building software you will frequently use libraries and tools from a third party. Since they have their own development lifecycles and versions we want to be able to define a specific version of that dependency to use in our software. We want to do that with a tool and a file.

For Rust we'll use the tool Cargo and our dependencies will be defined in the file Cargo.toml.

1
# cargo is installed along with Rust

Adding a Testing Library

We're going to use the testing library TK to write our tests.

Edit the file Cargo.toml and add TK as a testing dependency:

1
TK

Then we retrieve TK by running cargo update.

Finally we initialize TK by running TK.

The First Test

Create the file src/lib.rs with the following contents:

1
2
3
4
5
6
7
#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!("appleway", translate_word("apple"));
    }
}

Then run the test with the command cargo test to see the results:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Compiling ustray v0.1.0 (file:///Users/brian/temp/ustray)
error[E0425]: cannot find function `translate_word` in this scope
  --> src/lib.rs:10:32
   |
10 |         assert_eq!("appleway", translate_word("apple"));
   |                                ^^^^^^^^^^^^^^ not found in this scope
   |
help: possible candidate is found in another module, you can import it into scope
   |
1  | use translate_word;
   |

error: aborting due to previous error

error: Could not compile `ustray`.

To learn more, run the command again with --verbose.

Comments