0

I have a Rails controller I'm trying to write a new method for, and I'm running into an issue writing the tests for it. I've simplified the methods and tests repeatedly just trying to get something to pass but no luck. This is why I have now:

def new
 @map_id = 1
 puts @map_id
end
describe 'GET #new' do
 it 'simplified test' do
 get :new
 expect(assigns(:map_id)).to eq(1)
 end
end

The response I get from running this is:

Failure/Error: expect(assigns(:map_id)).to eq(1)
 
expected: 1
got: nil
 
(compared using ==)

I feel like there is something basic I'm missing here that is preventing get :new from correctly working. When I run it from the console, it prints out the 1, so I feel like there is something in the set Rails setup that I'm missing here.

My routes are set and confirmed with rails routes. The files are named correctly and other tests/routes are working fine.

asked Mar 24, 2025 at 3:05
2
  • 1
    Does this test invoke that action? Did you try to use binding.irb inside this action while testing with RSpec? Do you have some code that overrides this instance variable? Commented Mar 24, 2025 at 11:39
  • 1
    Please show the complete code (ofcourse your simplified version only) in the controller file and the spec file for it to share any insights. Commented Mar 24, 2025 at 12:44

1 Answer 1

0

Using the binding.irb tool mentioned by @mechnicov, I was able to determine that instead of routing to the new method, I was getting an unauthorized viewer message. Turns out there was some legacy authorization code that I needed to account for in my tests.

Specifically, I added the pry gem to my Gemfile, updated the test to this:

describe 'GET #new' do
 it 'simplified test' do
 get :new
 binding.pry
 expect(assigns(:map_id)).to eq(1)
 end
end

Then I ran the test, and examined the response object (which is what this controller is for), then investigated its contents.

answered Mar 24, 2025 at 20:14
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.