如何测试模型实例方法?

How to test a model instance method?

我在实施 Rspec 时遇到了一些麻烦。我有三个模型; PostTaggingTag

app/models/tag.rb

class Tag < ApplicationRecord
  # associations
  has_many :taggings
  has_many :posts, through: :taggings

  # validations
  validates :name, presence: true, uniqueness: { case_sensitive: false }

  # returns a list of posts that are belonging to tag.
  def posts
      ...
  end
end

我能够为关联和验证编写规范,但坚持为 def posts ... end 的实例方法编写规范。有人可以简要解释如何编写此规范吗?我是 Rspec 的新手,所以请多多包涵。

spec/models/tag_spec.rb

require 'rails_helper'

RSpec.describe Tag, type: :model do
  describe "Associations" do
    it { should have_many(:posts).through(:taggings) }
  end

  describe "Validations" do
    subject { FactoryBot.create(:tag) }

    it { should validate_presence_of(:name) }
    it { should validate_uniqueness_of(:name).case_insensitive }
  end

  describe "#posts" do
    # need help
  end

end

你可以这样做:

describe '#posts' do
  before do
    let(:tag) { Tag.create(some_attribute: 'some_value') }
    let(:tagging) { Tagging.create(tag: tag, some_attribute: 'some_value') }
  end

  it "tag should do something" do
    expect(tag.posts).to eq('something')
  end

  it "tagging should do something" do
    expect(tagging.something).to eq('something')
  end

end 

这将允许您在 Tag 上测试实例方法。基本上,您想在 before 块中构建要测试的对象,并在 it 块中调用它们的实例方法。