2015-07-20 96 views
1

现在能够在rspec的未定义的方法`的has_many”为

错误来测试has_many关系:

Failures: 

    1) Account associations 
    Failure/Error: it { should has_many :account_members} 
    NoMethodError: 
     undefined method `has_many' for #<RSpec::ExampleGroups::Account::Associations:0x007feaac7ea470> 
    # ./spec/models/account_spec.rb:13:in `block (3 levels) in <top (required)>' 

规格/型号/ account_spec.rb

require 'rails_helper' 

describe Account, type: :model do 

    context "valid Factory" do 
    it "has a valid factory" do 
     expect(build(:account)).to be_valid 
    end 
    end 

    context "associations" do 
    it { should belong_to :creator } 
    it { should has_many :members } 
    end 

    context "validations" do 
    before { create(:account) } 

    context "presence" do 
     it { should validate_presence_of :name } 
    end 
    end 

end 

规格/工厂。 /accounts.rb

FactoryGirl.define do 
    factory :account do 
    name {Faker::Company.name} 

    association :creator 
    end 

end 

应用程序/模型/ account.rb

class Account < ActiveRecord::Base 

    extend FriendlyId 
    friendly_id :name, use: :slugged 

    acts_as_paranoid 

    belongs_to :creator, class_name: "User", foreign_key: :created_by_id 
    has_many :invitations 
    has_many :members, class_name: "AccountMember" 

    # validations 
    validates :name, presence: true 

    # Methods 

    def should_generate_new_friendly_id? 
    name_changed? 
    end 

end 
+0

测试ActiveRecord方法是徒劳的,因为它们已经过测试 – Nermin

+0

'rspec-rails'不提供这样的匹配器。你可以安装'shoulda-matchers' gem来获得这些。 – Pavan

+0

我已将它添加到'rails_helper.rb'中 - 要求“shoulda/matchers” –

回答

1

如果使用shoulda-matchers,那么它应该是have_manyhas_many

require 'rails_helper' 

describe Account, type: :model do 

    context "valid Factory" do 
    it "has a valid factory" do 
     expect(build(:account)).to be_valid 
    end 
    end 

    context "associations" do 
    it { should belong_to :creator } 
    it { should have_many :members } #here 
    end 

    context "validations" do 
    before { create(:account) } 

    context "presence" do 
     it { should validate_presence_of :name } 
    end 
    end 

end 

有关更多信息,请参阅此Documentation

+1

非常感谢@Pavan –

相关问题