新模型

时间:2016-01-17 08:15:11

标签: ruby-on-rails ruby methods rspec undefined

我创建了一个名为SponsoredPost的模型,其中包含title:string, body:text and price:integer个属性。 这个新模型假设是我拥有的Topic模型的孩子。 这是它的Rspec:

RSpec.describe SponsoredPost, type: :model do
  let(:topic) {Topic.create!(name: RandomData.random_sentence,description: RandomData.random_paragraph)}
  let(:sponsored_post) { topic.sponsored_posts.create!(title: RandomData.random_sentence, body: RandomData.random_paragraph, price: 99) }
  it { should belong_to(:topic) }

  describe "attributes" do

    it "should respond  to title" do
      expect(sponsored_post).to respond_to(:title)
    end
    it "should respond to body" do
      expect(sponsored_post).to respond_to(:body)
    end
    it "should respond to price" do
      expect(sponsored_post).to respond_to(:price)
    end
  end
end

SponsoredPost模型:

class SponsoredPost < ActiveRecord::Base
  belongs_to :topic
end

主题模型:

class Topic < ActiveRecord::Base
  has_many :posts
  has_many :sponsored_posts
  has_many :posts, dependent: :destroy
  has_many :sponsored_posts, dependent: :destroy
end

4次测试中有3次失败并出现错误:

 undefined method `sponsored_posts' for #<Topic:0x007fde82176570>

我可能做错了什么?

2 个答案:

答案 0 :(得分:0)

  

主题的未定义方法`spons_posts':0x007fde82176570

您应该在Topic模型上设置 关联

class Topic < ActiveRecord::Base
  has_many :sponsored_posts
end

<强> 更新

Topic模型中有拼写错误,如果仔细观察,您已将其定义为sponsered_posts,其中sponsored_posts

答案 1 :(得分:0)

您还必须在Topic模型中定义反向关系。

has_many :sponsored_posts