Unit Testing Models
Rails generates a test infrastructure for you already. If you look at the file tree you will see a whole directory for tests. Inside will be a subdirectory just for your models. That subdirectory will come with test files for every model generated by rails.
An example file path for one of the test files might be something like: project/test/models/model_test.rb
Assertions
We can tell our test framework whether our code passes or fails by using assertions. An assertion is a method call that tells the framework what we expect to be true. The simplest assertion is the assert method, which expects its argument to be true. If it is, nothing special happens. However, if the argument to assert is false, the assertion fails. The framework will output a message and will stop executing the test method containing the failure.
An example test:
1
2
3
4
5
6
7
8
9
test "beverage attributes must not be empty" do
beverage = Beverage.new
assert beverage.invalid?
assert beverage.errors[:title].any?
assert beverage.errors[:featured_image].any?
assert beverage.errors[:ingredient_section].any?
assert beverage.errors[:instruction_section].any?
assert beverage.errors[:description].any?
end
Here we expect that an empty beverage model won’t pass the validations we made, so we can express that expectation by asserting that an empty beverage is not valid and will contain error messages.
Running unit tests
We can run out unit tests by issuing the rails test:models command.