继续对Answer模型进行测试失败

时间:2017-10-07 17:44:23

标签: ruby-on-rails ruby

我正在为一个类项目构建一个reddit克隆,而我的Answer模型一直都没有通过测试。

answer_spec.rb:

require 'rails_helper'

RSpec.describe Answer, type: :model do
    let(:question) { Question.create!(title: "New Question Title", body: "New Question Body", resolved: false) }
    let(:answer) { Answer.create!(body: "New Answer Body", question: question) }

    describe "attributes" do
        it "has a body attribute" do
            expect(Answer).to have_attributes(body: "New Answer Body")
        end
   end
end

我在运行时遇到了失败的原因:

Failures:

1) Answer attributes has a body attribute
 Failure/Error: expect(Answer).to have_attributes(body: "New Answer Body")
   expected Answer(id: integer, body: text, questions_id: integer, created_at: datetime, updated_at: datetime) to respond to :body with 0 arguments
 # ./spec/models/answer_spec.rb:9:in `block (3 levels) in <top (required)>'

Finished in 0.02163 seconds (files took 1.94 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/models/answer_spec.rb:8 # Answer attributes has a body attribute

有人可以帮我这个吗?

感谢。

修改

不包括答案类的道歉

class Answer < ApplicationRecord
    belongs_to :question
end

3 个答案:

答案 0 :(得分:1)

您正在设置Answer类的期望值 - 而不是let块中定义的实例。

require 'rails_helper'

RSpec.describe Answer, type: :model do
    let(:question) { Question.create!(title: "New Question Title", body: "New Question Body", resolved: false) }
    let(:answer) { Answer.create!(body: "New Answer Body", question: question) }

    describe "attributes" do
        it "has a body attribute" do
            expect(answer).to have_attributes(body: "New Answer Body")
        end
   end
end

通过我将它写成:

expect(answer.body).to eq "New Answer Body"

答案 1 :(得分:0)

看起来您没有使用let语句中的:answer实例。

请改为answer小写:

expect(answer).to have_attributes(body: "New Answer Body")

答案 2 :(得分:0)

  1. 您的数据库架构不同。它使用id,title,body等 问题和外键问题_id的答案。你不是 为要建立的关系指定此id。你是 只是传递整个对象而不是键。改用工厂女孩 如果您喜欢这种方式,请指定关联,或者只是传递外键。
  2. 另一点已经被其他人先前指出过了 评论者。您测试实例对象而不是类对象 属性。类是ruby类的对象,它会有 ruby的属性Class不是你的类所以使用你的实例 用来测试行为的类。