【问题标题】:Rspec error "undefined method " for new model新模型的 Rspec 错误“未定义方法”
【发布时间】:2016-04-22 13:01:34
【问题描述】:

我用title:string, body:text and price:integer 属性创建了一个名为SponsoredPost 的模型。 这个新模型应该是我拥有的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>

我做错了什么?

【问题讨论】:

  • class Topic &lt; ActiveRecord::Base has_many :posts has_many :sponsered_posts has_many :posts, dependent: :destroy has_many :sponsered_posts, dependent: :destroy end
  • 错字 - sponsered_posts 在模型中。将其更改为sponsored_posts
  • 修复了还是同样的问题

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


【解决方案1】:

主题的未定义方法“赞助帖子”:0x007fde82176570

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

class Topic < ActiveRecord::Base
  has_many :sponsored_posts
end

更新:

您在Topic 模型中有错字,如果仔细观察,您已将其定义为sponsered_posts,它应该是sponsored_posts

【讨论】:

  • 我刚才忘了放在这里抱歉。
  • 修复它,但我仍然遇到同样的问题。
  • 你在哪里修的?并尝试重新启动服务器
  • 修复了Topic 模型中sponsered_postssponsored_posts 的问题。
  • 谢谢你这实际上结束了我只是不小心忘记修复sponsored_posts之一但现在一切正常找到谢谢你:)
【解决方案2】:

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

has_many :sponsored_posts

【讨论】:

  • 我刚才忘了放在这里抱歉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多