Rspec 错误 "undefined method " 新模型
Rspec error "undefined method " for new model
我创建了一个名为 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
赞助商模特:
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>
我做错了什么?
undefined method `sponsored_posts' for Topic:0x007fde82176570
您也应该在 Topic
模型上设置 关联
class Topic < ActiveRecord::Base
has_many :sponsored_posts
end
更新:
您在 Topic
模型中有一个错字,如果您仔细观察,您将其定义为 sponsered_posts
而它应该是 sponsored_posts
您还必须在 Topic
模型中定义逆关系。
has_many :sponsored_posts
我创建了一个名为 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
赞助商模特:
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>
我做错了什么?
undefined method `sponsored_posts' for Topic:0x007fde82176570
您也应该在 Topic
模型上设置 关联
class Topic < ActiveRecord::Base
has_many :sponsored_posts
end
更新:
您在 Topic
模型中有一个错字,如果您仔细观察,您将其定义为 sponsered_posts
而它应该是 sponsored_posts
您还必须在 Topic
模型中定义逆关系。
has_many :sponsored_posts