Amirol Ahmad
Amirol Ahmad

Reputation: 542

Rspec has_one relation error when updating

I have User (which is I used Devise) and Profile model where User has_one Profile as their relationship. I got an error when run the rspec test. Below is my spec to handle when user is updating his/her profile.

spec/controller/profiles_controller_spec.rb

RSpec.describe ProfilesController, type: :controller do
  let(:profile) { FactoryGirl.create(:profile) }
  let (:valid_attributes) { FactoryGirl.attributes_for(:profile) }
  let (:invalid_attributes) { FactoryGirl.attributes_for(:profile).merge({fname: nil}) }
  let(:user) { FactoryGirl.create(:user) }
  let(:valid_session) { sign_in(user) }

  describe "PUT #update" do
    before { valid_session }

    context "with valid attributes" do
      it "saves valid profile" do
        expect do
          put :update, { id: profile.id, profile: { fname: "Cena" } }
        end.to change{ profile.reload.fname }.to("Cena")
      end
    end

spec/factories/profiles.rb

FactoryGirl.define do
  factory :profile do
    user 
    fname "John"
    lname "Doe"
    avatar "my_avatar"
  end
end

app/controller/profiles_controller.rb

class ProfilesController < ApplicationController

private

  def user_params
    params.require(:user).permit(:id, :login, :email,
      profile_attributes: [
        :id, :user_id, :fname, :lname, :avatar, :avatar_cache
      ])
  end

end

And here is the error when run rspec spec/controllers/accounts_controller_spec.rb

Failures:

  1) AccountsController PUT #update with valid attributes saves valid profile
     Failure/Error: put :update, {id: profile.id, user_id: user.id, profile: { fname: "Cena" }}
     ActionController::ParameterMissing:
       param is missing or the value is empty: user

Upvotes: 1

Views: 359

Answers (2)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

  let(:user) { FactoryGirl.create(:user) }
  let(:profile) { FactoryGirl.create(:profile, user_id: user.id ) }

  describe "PUT #update" do
    before { valid_session }

    context "with valid attributes" do
      it "saves valid profile" do
        expect do
          put :update, id: user.id, user: { profile_attributes: { user_id: user.id, fname: "Cena" } }
        end.to change{ profile.reload.fname }.to("Cena")
      end
    end
  end

Upvotes: 1

tyamagu2
tyamagu2

Reputation: 969

The profiles_controller.rb code you posted is missing the update action (and also the class name is AccountController), but I guess you are doing something like user.update(user_params).

If that's the case, as the error says, the params passed from the controller spec does not have :user key, and that is causing the error.

Assuming from the #user_params method and the error, the params passed to the post in controller spec needs to look like the following:

{ 
  user: {
    id: xxx, ...,
    profile_attributes: {
      id: xxx, 
      fname: xxx, ...
    }
   }
}

Upvotes: 0

Related Questions