我创建了一个名为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>
我可能做错了什么?
答案 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