我有一個控制器操作'show',我試圖測試。控制器看起來是這樣的:繼續在Rspec中獲取未定義的方法錯誤
def show
@contest = Contest.find(params[:contest_id])
@my_entry = current_user.entries.where(contest_id: params[:contest_id]).sort_by { |entry| -entry.total_points}
@points_per_player = @my_entry[0].points_per_player
@total_points = @my_entry[0].total_points
@opponents = @contest.entries.where.not(user_id: current_user.id).sort_by { |entry| -entry.total_points}
@opponent_squad = Squad.find(@opponents[0].squad_id)
@opponent_points = @opponents[0].points_per_player
end
和show動作規範是這樣的:
describe 'GET /show' do
let!(:user) { create(:user) }
let!(:squad_1) { create(:squad) }
let!(:squad_2) { create(:squad) }
let!(:contest) { create(:contest) }
let!(:my_entry) { create(:entry, user_id: user.id, contest_id: contest.id) }
let!(:opponents) { [:squad_1, :squad_2] }
let!(:opponent_squad) { create(:squad) }
before :each do
sign_in user
controller.instance_variable_set(:@opponent_squad, :squad)
get :show, contest_id: contest.id
end
it "renders the show template" do
(expect (response.status)).to eql(200)
(expect (assigns(:opponents))).to eql([:squad_1, :squad_2])
(expect (assigns(:opponent_squad))).to eql(:squad)
end
end
Rspec的不斷拋出的錯誤「未定義的方法`squad_id」的零:NilClass」,這是我認爲是指在表演動作倒數第二行,即:
@opponent_squad = Squad.find(@opponents[0].squad_id)
任何想法,爲什麼發生這種情況,如何解決? (注意:我非常新Rspec的)
非常感謝!有效! – NdaJunior