2015-07-20 59 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 –

相關問題