我在实施Rspec方面遇到了一些麻烦。我有三个型号; Post
,Tagging
和Tag
。
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的新手所以请耐心等待。
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
答案 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
块中调用它们上的实例方法。