Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ruby on rails - session available in some rspec files and not others. how come?

In trying to test some sign-in/out functionality I want to delete some information from the session. I found out I couldn't access the sessions at all. I kept getting the error: undefined method `session' for nil:NilClass.

But then to my surprise I found out I could access session from other rspec pages. Additional details are below. My question is: Why can I access session from some files and not others? And how can I make it so that I can access session in my second example below?

Details File: spec/controllers/tenants_controller_spec.rb

require 'spec_helper'

describe TenantsController do
  specify { session[:tag].should == 'abc' }
end

File: spec/requests/test.rb

require 'spec_helper'

describe 'Test' do
  specify { session[:tag].should == 'abc' }
end

When I run the first file through rspec I get:

Failure/Error: specify { session[:tag].should == 'abc' }
  expected: "abc"
    got: nil (using ==)

Which is good. This should fail for that reason.

But, when I run the second file, I get:

 Failure/Error: specify { session[:tag].should == 'abc' }
 NoMethodError:
   undefined method `session' for nil:NilClass

So why is session an undefined method here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your 2nd test is a "request" spec which is an integration test. These are designed to simulate the browser and the helpers you get let you click buttons and fill out forms and assert text, tags on the page. It's the wrong level of abstraction for inspecting the session object.

If you want to stub out authentication, e.g. best to go through the app. See, e.g. here: Stubbing authentication in request spec

Know that integration tests are "exploratory" or "smoke" tests, high level tests that check the seams between components, not the guts of the components themselves. They're the most expensive to write and maintain. Use controller specs for verifying session stuff and move all business logic to the models where it's easiest to test.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...