RSpec中调用create(:user)后User.all返回nil,如何获取创建的用户?
User.all Doesn't Return the Created User I totally get this—this is a super common gotcha with RSpec's let helper! Let's break down why this is happening and how to fix it quickly.
Why User.all is coming back empty/nil
RSpec's let uses lazy evaluation: the block you wrote (create(:user)) won't actually run until the first time you reference the user variable in your test example. Since your current test doesn't use user anywhere, the user record never gets saved to the database—so User.all has nothing to return.
Solution 1: Reference the user variable in your example
The simplest fix is just to call user somewhere in your test block. This triggers the creation of the user record:
describe 'GET #show' do let(:user) { create(:user) } it 'returns HTTP OK response with expected body' do user # This line kicks off the create call puts User.all # Now this will include your created user end end
Solution 2: Use let! instead of let
If you don't want to add an extra line just to reference the variable, switch to let! (with an exclamation mark). let! is eagerly evaluated—it runs the block before the example starts, so the user is created even if you never explicitly call user in the test:
describe 'GET #show' do let!(:user) { create(:user) } # Note the ! here it 'returns HTTP OK response with expected body' do puts User.all # This will include your created user right away end end
Bonus: Make it a proper test assertion
Instead of just printing User.all, you might want to add a concrete assertion to validate the user exists—this is way more useful for a test than debug output:
it 'returns HTTP OK response with expected body' do expect(User.count).to eq(1) expect(User.first).to eq(user) end
内容的提问来源于stack exchange,提问作者Leo Jiang

