繁体   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