对我来说看起来不错 - 这是另一个示例,它采用了一个测试关联和验证的类 Listing。
class Listing < ActiveRecord::Base
#Associations
belongs_to :user
belongs_to :category, inverse_of: :listings
has_many :photos, dependent: :destroy
has_many :watches
has_many :watchers, -> { uniq }, :through => :watches
has_many :offers, dependent: :destroy
has_many :feedbacks
belongs_to :location, :dependent => :destroy
# Association validations
validates_presence_of :category
validates_presence_of :user
# Attribute validations
validates_presence_of :title, message: "Please add a title."
validates_presence_of :subtitle, message: "Please add a subtitle."
validates_presence_of :price, message: "Please add a price."
validates_presence_of :title, message: "Please select a condition."
require 'rails_helper'
RSpec.describe Listing, type: :model do
#Associations
it { should belong_to(:user) }
it { should belong_to(:category) }
it { should have_many(:photos) }
it { should have_many(:watches) }
it { should have_many(:watchers).through(:watches) }
it { should have_many(:offers) }
it { should belong_to(:location).dependent(:destroy) }
#Association validations
it { should validate_presence_of(:category) }
it { should validate_presence_of(:user) }
#Attribute validations
it { should validate_presence_of(:title).with_message("Please add a title.") }
it { should validate_presence_of(:subtitle).with_message("Please add a subtitle.") }
it { should validate_presence_of(:price).with_message("Please add a price.") }
it { should validate_presence_of(:title).with_message("Please select a condition.") }
注意使用RSpec.describe Class, type: :model 来指定测试类型。
我会阅读 Shoulda 自述文件,其中详细说明了各种示例组中匹配器的可用性。它们提供了四类匹配器:
ActiveRecord 和 ActiveModel 匹配器仅在模型中可用
示例组,即那些用 type: :model 或在文件中标记的组
位于规格/型号下。
ActionController 匹配器仅在控制器示例中可用
组,即标记为 type: :controller 或位于文件中的组
在规范/控制器下。
路由匹配器也可以在路由示例组中使用,即,
那些带有 type: :routing 或位于下的文件中的标签
规格/路由。
独立匹配器在所有示例组中都可用。
在安排您的规范方面,旨在反映您的应用目录(或多或少)。
如果你有:
app/models/user.rb
app/services/
app/controllers/
app/presenters/
您可以通过以下方式进行镜像:
spec/models/user_spec.rb
spec/services/
spec/controllers/
spec/presenters/
然后您可能会有一些额外的规范文件夹,例如:
spec/features/ (a folder for integration/feature specs)
RSpec 文档对此有一些非常好的信息。