2016-07-25 6 views
1

belongs_tohas_manyという2つのモデルを以下のようにリンクしています。RSpec使用する場合はrespond_to

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のチェックを廃止しました。

答えて

1

私が知る限り、あなたは絶対に正しいです。 should have_manyshould belong_toを使用している限り、respond_toは必要ありません。あなたのコードはちょうどあなたがこのlist of RSpec Shoulda matchersを見てみることができます。この

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 

ようになります。

respond_toを使用するのに最適な時期は、モジュールをクラスに組み込み、そのクラスに特定のメソッドがあることを確認したいときです。例:

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 
関連する問題