2017-10-07 80 views
0

我正在爲類項目構建一個reddit克隆,並且我的答案模型始終未通過測試。爲答案保留失敗測試

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 
+0

沒有看到你的答案類的代碼,沒有太多的幫助可以給。但是測試結果指出了這個問題,你的Answer類對「body」沒有響應,這意味着它沒有名爲body的屬性。 – Kyle

+2

'expect(answer)'。 –

回答

0

它看起來像您不使用從您let語句的:answer實例。

試試這個answer小寫:

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

謝謝丹。試過,但現在我得到'ActiveModel :: MissingAttributeError: 無法寫未知屬性'question_id''。任何想法是從哪裏來的?謝謝。 – chocofan

+0

[This answer](https://stackoverflow.com/questions/20295710/activemodelmissingattributeerror-cant-write-unknown-attribute-ad-id-with-f)可能會有所幫助。 [此鏈接](https://stackoverflow.com/questions/30128651/activemodelmissingattributeerror-cant-write-unknown-attribute-user-id)。 ''answers'表在'schema.rb'中有'question_id'嗎? –

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 

g雖然我只是把它寫爲:

expect(answer.body).to eq "New Answer Body" 
0
  1. 你的數據庫架構是不同的。它使用ID,標題,正文等爲 問題和一個外鍵question_id的答案。您不是 指定此ID以建立關係。你只是傳遞一個完整的對象而不是關鍵字,而是 。使用工廠女孩 並指定關聯,如果你喜歡這種方式,或者只是傳遞外鍵。
  2. 另一點已被其他 評論者早先指出。您測試實例對象不是類對象具有 屬性。一個類是ruby類的一個對象,它會有 屬性的ruby的類不是你的類,所以使用你的 類的實例來測試行爲。