Rspec 测试:NoMethodError - nil.Nilclass 的未定义方法 'id'

Rspec Testing : NoMethodError - undefined method 'id' for nil.Nilclass

当我 运行 rspec 测试 Rails 中的控制器时,我在第二行收到错误 "NoMethodError : undefined method 'id' for nil.Nilclass"

params[:tag_id] 是前端传下来的,所以没法初始化。 我该如何纠正这个错误?

     #enables the id to be a name rather than just a number
    if (params[:tag_id].class) == String && (params[:tag_id]!= "alltags")
       tag_id = Tag.find_by(name: params[:tag_id]).id
    elsif params[:tag_id] == "alltags"
       tag_id = "alltags"
    else
       tag_id = params[:tag_id]
    end

添加rspec个测试用例

context "POST search_time_range" do
    it 'returns all data within a certain time range and where the tag_id matches' do
        params = {
            "range_start" => "2016-01-01",
            "range_end" => "2016-01-01",
            "tag_id" => "122"
        }

        post :search_time_range, params
        expect(response).to have_http_status(200)

    end

首先你有一个错误:

Tag.find_by(name: params[:tag_id]).id

应该是:

Tag.find_by(id: params[:tag_id]).id

或:

Tag.find(params[:tag_id]).id

params[:tag_id] is passed down from the front end

当您从您的规范发出请求时,您需要将 tag_id 传递到参数中。请记住,您需要仔细检查,在您的 rspec 中,您还在数据库中创建了一个有效的 Tag 记录,您将在传递的 params

中引用该记录

更新

context "POST search_time_range" do
    it 'returns all data within a certain time range and where the tag_id matches' do
        tag = Tag.create(name: '122')
        params = {
            "range_start" => "2016-01-01",
            "range_end" => "2016-01-01",
            "tag_id" => tag.name
        }

        post :search_time_range, params
        expect(response).to have_http_status(200)
    end
end

作为快速有效的解决方案。但最好将测试数据存储在某种固定装置中或使用 factory_girl.