In order to write a unit test case for model in rails 4, Let's suppose that we have a model city.rb which has some validations and associations.
#Rails 4.1.14.2 & ruby-2.1.7
Model path: my_app/app/models/city.rb, like...
class City < ActiveRecord::Base
has_many :users
belongs_to :country
validates_presence_of :name, :country_id, :code
# with other statement
end
In Unit-Test case for a model we create its factory, in factories folder, named cities.rb as table name in db. This file having model attribute and with dummy values
Path: my_app/test/factories/cities.rb
FactoryGirl.define do
factory :city do |f|
country_id 123
name 'myCity'
code 'mycode'
status true
end
end
In city.rb model, there are two model associations i.e. city belongs_to country and city has_many users. So we need to create factories files for country ans users.
Path: my_app/test/factories/countries.rb
FactoryGirl.define do
factory :country do |f|
name "India"
code 'IN'
end
end
Path: my_app/test/factories/users.rb
FactoryGirl.define do
factory :user do |f|
first_name 'name'
last_name 'last'
email 'fake@user.com'
password 'password'
gender 'Male'
country_id 1
city_id 12
end
end
Now create a file in units folder named city_test.rb for testing its association ans validations
Path: my_app/test/unit/city_test.rb
require 'test_helper.rb'
class CityTest < ActiveSupport::TestCase
test "validations of model" do
city_obj = build(:city,name: "")
assert_equal city_obj.save,false, "Validate presence of name"
city_obj = build(:city,country_id: "")
assert_equal city_obj.save,false, "Validate presence of country_id"
city_obj = build(:city,code: "")
assert_equal city_obj.save,false, "Validate presence of code"
end
def unit_test_for_has_many_user_association
city = create(:city)
u1 = create(:user,city_id: city.id,email: 'e1@unit.com')
u2 = create(:user,city_id: city.id,email: 'e2@test.com')
assert_equal city.users, [u1,u2]
end
Run your Test Case using command ...
ruby -I "lib:test" test/units/city_test.rb
Output:
Started
.
Finished in 0.589748669 seconds.
2 tests, 4 assertions, 0 failures, 0 errors, 0 pendings, 0 omissions, 0 notifications
0% passed
0 Comment(s)