RSpec 什么时候使用应该 respond_to

RSpec when to use it should respond_to

我有两个模型通过 belongs_tohas_many 关系链接在一起,如下所示。

Class OtherModel < ActiveRecord::Base
  belongs_to my_model
end

class MyModel < ActiveRecord::Base
  has_many other_models
end

我现在有相应的测试来验证它们是否具有如下所示的正确关系。

RSpec.describe MyModel, type: :model do
  it {should have_many(:other_models)}
  it {should respond_to(:other_models)}
end

RSpec.describe OtherModel, type: :model do
  it {should have_many(:my_model)}
  it {should respond_to(:my_model)}
end

对于这种关系,是否需要 respond_to,如果是,为什么?它检查 have_many 尚未检查的内容是什么?如果在这种情况下不需要respond_to,什么时候使用它比较合适?根据我目前的理解 have_many 已经验证该字段存在,因此废弃了 respond_to 检查。

据我所知,你是完全正确的。只要使用 should have_manyshould belong_to,就不需要 respond_to。您的代码可能看起来像这样

RSpec.describe MyModel, type: :model do
  it {should have_many(:other_models)}
end

RSpec.describe OtherModel, type: :model do
  it {should belong_to(:my_model)}
end

你也可以看看这个list of RSpec Shoulda matchers

使用 respond_to 的最佳时机是当您将模块包含到 class 中并且您想要确保 class 具有特定方法时。示例:

Class MyModel < ActiveRecord::Base
  include RandomModule
  has_many other_models
end

module RandomModule
  def random_calculation
    3 * 5
  end
end

RSpec.describe MyModel, type: :model do
  it {should have_many(:other_models)}
  it {should respond_to(:random_calculation)}
end