Introduction
Testing helps make sure your Rails app works correctly and keeps working as you add new features.
Testing helps make sure your Rails app works correctly and keeps working as you add new features.
rails generate test_unit:model ModelName rails test
test "should save valid user" do user = User.new(name: "Alice") assert user.save end
test "should not save user without name" do
user = User.new
assert_not user.save
endThis test file has two tests: one confirms a user with a name saves, the other confirms a user without a name does not save.
require "test_helper" class UserTest < ActiveSupport::TestCase test "valid user saves successfully" do user = User.new(name: "Bob") assert user.save end test "invalid user without name does not save" do user = User.new assert_not user.save end end
Writing tests early saves time by catching errors before users see them.
Rails encourages testing by generating test files automatically.
Tests act like safety nets when changing or adding code.
Testing ensures your Rails app works as expected.
It helps catch bugs early and keeps your app stable.
Rails has built-in tools to make testing easy and part of your workflow.
rails test.test "should save user" do user = User.new(name: "Alice") assert user.save end
assert user.save doesuser.save returns true, meaning the user saved successfully.user.save returns false, causing the assertion to fail and the test to fail.assert user.save expects true. -> Option Ctest "should create post" do post = Post.new(title: "Hello") assert post.save end
post.save might failPass the test and this pattern moves unknown