If you’re new to unit testing with Rails (I am) be sure to implement a setup method to instantiate your model object. If you look at the basic shell for unit tests you’ll notice that a setup method is not defined. Yet if you view a basic functional test you’ll see that a setup method does exist.
When creating my unit test I added a basic method that tested that a user was created successfully:
def test_create
assert_kind_of User, @user
assert_equal 1, @user.id
assert_equal “dennis”, @user.first_name
end
The problem was that the user instance didn’t exist. It turns out I needed to instantiate it through the setup method which is very basic:
def setup
@user = User.find(1)
end
The @user instance variable is accessible througout the unit test, which makes testing very simple. If you’re testing different models be sure to implement the setup method, it will come in very handy.