简体   繁体   中英

Sporadically failing rspec test

I have a test that passes most of the time:

....

Finished in 1.58 seconds
4 examples, 0 failures

Randomized with seed 29966

But on occasion will fail:

.F..

Failures:

  1) Admin::SessionsController POST create authenticates correct users submissions
     Failure/Error: expect(session[:user_id]).to be @user.id

       expected #<Fixnum:3> => 1
            got #<NilClass:4> => nil

       Compared using equal?, which compares object identity,
       but expected and actual are not the same object. Use
       `expect(actual).to eq(expected)` if you don't care about
       object identity in this example.
     # ./spec/controllers/admin/sessions_controller_spec.rb:12:in `block (3 levels) in <top (required)>'

Finished in 1.24 seconds
4 examples, 1 failure

Failed examples:

rspec ./spec/controllers/admin/sessions_controller_spec.rb:10

Is there any particular rhyme or reason anyone can see in this?

spec:

  describe "POST create" do
    it "authenticates correct users submissions" do
      post :create, email: @user.email, password: @user.password
      expect(session[:user_id]).to be @user.id
    end

    it "correctly sets @invalid flag" do
      post :create, email: "wrong", password: "wrong"
      assigns(:invalid).should be_true
    end
  end

The controller action being tested:

  def create
    user = Admin::User.authenticate(params[:email], params[:password])
    if user
      session[:user_id] = user.id
      redirect_to admin_root_path
    else
      @invalid = true
      render :new
    end
  end

Any help would be much appreciated. Let me know if more details are needed.

It's likely to be because RSpec runs tests in random order by default.

It looks like the test you refer to is being called before user is created. If you want to resolve it make sure that user is created in the before block. Alternatively it could be because user already exists and therefore the action fails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM