簡體   English   中英

Ruby on Rails 如何修復 NoMethodError: undefined method `id' for nil:NilClass

[英]Ruby on Rails how to fix NoMethodError: undefined method `id' for nil:NilClass

我正在嘗試對我的Response controller 進行測試,其中沒有人登錄,如果有人試圖在沒有先登錄的情況下發布對祈禱Request的有效響應,應用程序應重定向到登錄 url。 我在requests.yml文件中有一些測試requests ,當我嘗試在測試代碼中使用其中一個請求時,試圖提取它的id時,我收到一條錯誤消息,說我有一個 NilClass 錯誤並且無法獲取id

這是我的測試代碼:

require "test_helper"

class ResponsesControllerTest < ActionDispatch::IntegrationTest

  def setup
    @request = requests(:askingfororange)
    @response = responses(:responsetoorange)
    @user = users(:michael)
  end

  test "should redirect create when not logged in" do
    assert_no_difference 'Response.count' do
      post responses_path, params: { response: { content: "Lorem ipsum",
                                                user_id: @user.id,
                                                request_id: @request.id } }
    end
    assert_redirected_to login_url
  end

end

這是我的 requests.yml 文件:


askingfororange:
  content: "I need more oranges in my life. Please pray."
  created_at: <%= 10.minutes.ago %>
  user: michael

askingaboutpi:
  content: "Does pi matter in spirituality? Please pray for me to know!"
  created_at: <%= 3.years.ago %>
  user: michael

askingforcat:
  content: "Do cats help with spiritual health? Pray for me to find out!"
  created_at: <%= 2.hours.ago %>
  user: michael

askingforlime:
  content: "I need more limes in my life, please pray."
  created_at: <%= 3.days.ago %>
  user: archer

most_recent:
  content: "My most recent prayer request is... tada!"
  created_at: <%= Time.zone.now %>
  user: michael

<% 30.times do |n| %>
request_<%= n %>:
  content: <%= Faker::Lorem.sentence(word_count: 15) %>
  created_at: <%= 42.days.ago %>
  user: michael
<% end %>

當我運行我的測試套件時,我得到以下信息:

ERROR ResponsesControllerTest#test_should_redirect_create_when_not_logged_in (0.36s)
Minitest::UnexpectedError:         NoMethodError: undefined method `id' for nil:NilClass

                                                        request_id: @request.id } }
                                                                            ^^^

@request已經被ActionDispatch::IntegrationTest使用,並且在每個測試的頂部重置為nil 選擇一個不同的變量名。

參見https://github.com/rails/rails/blob/8015c2c2cf5c8718449677570f372ceb01318a32/actionpack/lib/action_dispatch/testing/integration.rb#L152

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM