Wings2fly
Wings2fly

Reputation: 937

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

When I am running rspec testing for a controller in Rails, I get the error "NoMethodError : undefined method 'id' for nil.Nilclass" at the second line.

params[:tag_id] is passed down from the front end, so I can't initialize that. How would I correct this error?

     #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

Adding rspec test case

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

Upvotes: 1

Views: 1863

Answers (1)

AntonTkachov
AntonTkachov

Reputation: 1784

First of all you have a bug in:

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

Which should be:

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

Or:

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

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

You need to pass tag_id into params when you make request from your spec. Keep in mind that you need to double check, that in your rspec you also create a valid Tag record in your database, which you will refer in your passed params

Update

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

As a quick and valid solution. But better to store your test data either in some kind of fixtures or use factory_girl.

Upvotes: 2

Related Questions