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
(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
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
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
$ bin/rspec spec/models/post_spec.rb
Recommended Posts