如何测试模型实例方法?

时间:2018-04-28 13:13:15

标签: ruby-on-rails rspec rspec-rails

我在实施Rspec方面遇到了一些麻烦。我有三个型号; PostTaggingTag

应用程序/模型/ 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的新手所以请耐心等待。

规格/模型/ 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

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

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块中调用它们上的实例方法。