NoMethodError: undefined method for nil:NilClass in CI
A method was called on nil. Somewhere a lookup, fetch, or assignment returned nil where the code assumed a real object, and the next method call fails.
What this error means
A test fails with NoMethodError naming a method "for nil:NilClass". The failing line is where the nil is used, but the real bug is wherever the nil originated (a missing record, an unset env, an empty hash key).
NoMethodError:
undefined method `email' for nil:NilClass
# ./app/mailers/welcome_mailer.rb:8:in `greet'Common causes
Lookup returned nil
find_by, [], dig, or a fixture/factory returned nil because the record or key was not present in the test database or setup.
Unset environment or config in CI
A value read from ENV or credentials is nil on the runner because the variable was never set in the CI environment.
Order-dependent setup
A previous step or before block did not run (or ran in a different order in CI), leaving an instance variable nil.
How to fix it
Trace the nil to its source
- Read the backtrace to the line that calls the method, then find where that receiver was assigned.
- Add a guard or assertion before the call to confirm whether the value is nil at that point.
- Check that the test setup actually creates the record or sets the value the code reads.
Make missing values explicit
Fail fast on a missing required value instead of letting a nil propagate to a confusing line.
api_key = ENV.fetch('API_KEY') # raises a clear KeyError if unset
user = User.find_by!(id: id) # raises RecordNotFound, not nilHow to prevent it
- Use fetch and find_by! so missing values raise where they originate.
- Set required ENV vars in the CI job env, not only locally.
- Keep test setup self-contained so each example creates its own data.