Darpan
Darpan

Reputation: 5795

Unit test (Rspec) cannot update `current_user` in Rails

I have a unit test of this type -

describe "#test_feature" do
  it "should test this feature" do
    sign_in @group_user
    get :get_users, {name: "darpan"}
    expect(@group_user.user_detail.name).to eq("darpan")
    sign_out @group_user
  end
end

and function get_users is like this -

def get_users
  quick_start = current_user.user_detail.quick_start
  current_user.user_detail.update_attribute(:name, "darpan")
  render :json => :ok
end

Now, when I run above rspec, current_user's user_detail gets updated(checked with binding.pry), but logged in user @group_user's user_detail does not get updated. Hence my expect fails.

What wrong am I doing in testing this function?

Upvotes: 0

Views: 145

Answers (1)

moveson
moveson

Reputation: 5213

You may need to reload your resource in RSpec in order to see the change:

describe "#test_feature" do
  it "should test this feature" do
    sign_in @group_user
    get :get_users, {name: "darpan"}
    @group_user.reload   # Reloads information from the database
    expect(@group_user.user_detail.name).to eq("darpan")
    sign_out @group_user
  end
end

Upvotes: 5

Related Questions