我创建了一个名为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
endSponsoredPost模型:
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
end4次测试中有3次失败时出错:
undefined method `sponsored_posts' for #<Topic:0x007fde82176570>我做错什么了?
发布于 2016-01-17 08:17:37
主题的未定义方法`sponsored_posts‘:0x007fde82176570
您也应该在模型上设置Topic关联
class Topic < ActiveRecord::Base
has_many :sponsored_posts
end更新:
您在Topic模型中有一个错误,如果仔细观察,您已经将其定义为sponsered_posts,其中应该是sponsored_posts
发布于 2016-01-17 08:17:50
您还必须在Topic模型中定义逆关系。
has_many :sponsored_postshttps://stackoverflow.com/questions/34836409
复制相似问题