未定义的方法`has_many'为

时间:2015-07-20 14:05:31

标签: ruby-on-rails ruby-on-rails-4 rspec

现在能够在rspec中测试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

1 个答案:

答案 0 :(得分:1)

如果您使用的是shoulda-matchers,那么它应该是have_many而不是has_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