Testing model with RSpec

model test preparation

This time, we will test whether the Post model has a title column and the number of characters.

app/models/post.rb


class Post < AplicationRecord
  belongs_to :user
  validates :title, presence: true, length: {maximum: 20}
end

Create file

(1) Create a models folder and a factories folder under spec, and create a file of the model you want to test. This time create spec/models/post_spec.rb

② Enable Factroy Bot. If you use it, you can register DB and build model like user = create (: user). Create a support folder and factory_bot.rb file under spec and describe the following. Create two files, post_spec.rb user_spec.rb, to test that you can only post if the user is logged in.

spec/support/factroy_bot.rb


RSpec.configure do |config|
  config.include FactroyBot::Syntax::Methods
end

③ Edit spec/rails_helper.rb

spec/rails_helper.rb


require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../config/environment', __dir__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'support/factory_bot'

begin
  ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
  puts e.to_s.strip
  exit 1
end
RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = true
  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!
  
  
  #Not relevant in this article, but system_Description for starting chrome in headless mode in spec
  config.before(:each) do |example|
    if example.metadata[:type] == :system
      if example.metadata[:js]
        driven_by :selenium_chrome_headless, screen_size: [1400, 1400]
      else
        driven_by :rack_test
      end
    end
  end
  
  #Description about capybara
  config.include Capybara::DSL
end

Creating dummy data

spec/factories/user.rb


FactoryBot.define do
  factory :user do
    name {Faker::Name.name}
    email {Faker::Internet.email}
    password {'password'}
    password_confirmation {'password'}
  end
end

spec/factories/post.rb


FactoryBot.define do 
  factory :post do
    body {Faker::Lorem.characters(number: 20)}
    user
  end
end

Creating test code

spec/models/post_spec.rb


require 'rails_helper'

RSpec.describe 'post model test', type: :model do
  describe 'validation test' do
    #Use dummy data created by factories
    let(:user) {FactoryBot.create(:user)}
    let!(:post) {build(:post, user_id: user.id)}
    #test_Create a post and check if you can register in the blank
    subject {test_post.valid?}
    let(:test_post) {post}
    
    it 'The title column is not blank' do
      test_post.title = ''
      is_expected.to eq false;
    end

    it 'False if 21 characters or more' do
      post.title = Faker::Lorem.characters(number: 21)
      expect(post).to eq false;
    end
  end
end

Run RSpec

$ bin/rspec spec/models/post_spec.rb

Recommended Posts

Testing model with RSpec
Testing with com.google.testing.compile
[Ruby on Rails] Model test with RSpec
[Rails] Test with RSpec
Use webmock with Rspec
Test Nokogiri with Rspec.
[Rails] From test preparation to model unit testing [RSpec]
Check CSV value with RSpec
Introduction to RSpec 3. Model specs
Test Active Strage with RSpec
Streamline Java testing with Spock
Test GraphQL resolver with rspec
REST API testing with REST Assured
Automatic API testing with Selenium + REST-Assured
Test with RSpec + Capybara + selenium + chromedriver
RSpec ~ Task model validation test creation
About app testing RSpec (unit test)
Copy and paste test with RSpec
Let's unit test with [rails] Rspec!
[Ruby on Rails] View test with RSpec
[Note] How to get started with Rspec
Getting Started with Parameterization Testing in JUnit
[Ruby on Rails] Controller test with RSpec
What is the model test code testing
Automate integration testing with Maven Failsafe plugin
Notes on creating a many-to-many Factory with Rspec and testing it with SystemSpec [RSpec, FactoryBot]