Reputation: 410
This is my create method in users_controller.rb
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to users_url, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:name, :password, :password_confirmation)
end
end
And This is my Users_controllers_spec.rb file
require 'rails_helper'
RSpec.describe UsersController, type: :controller do
describe "Post /create" do
let(:user){build(:user)}
it "should create user" do
expect(User).to receive(:new).with({name: 'Naik', password: 'secret', password_confirmation: 'secret'}).and_return(User)
post :create, user: {name: 'Naik', password: 'secret', password_confirmation: 'secret'}
expect(flash[:success]).to eq("User was successfully created.")
expect(response).to redirect_to(users_path)
end
end
end
And this is the error I am getting. Am I missing something? I am new to Rspec testing so any advice on how to solve it would be appreciated.
Thank you.
Upvotes: 4
Views: 2126
Reputation: 581
This seems to be an issue only when using Rails 5. Here is how this can be fixed: How to expect a Params hash in RSpec in Rails 5?
Basically this should be:
expect(User).to receive(:new).with(ActionController::Parameters.new( name: 'Naik', password: 'secret',password_confirmation: 'secret').permit(:name, :password, :password_confirmation)).and_return(user)
expect(user).to receive(:save).and_return(true) # stub the `save` method
post :create, user: {name: 'Naik', password: 'secret', password_confirmation: 'secret'}
# ...and then your expectations
Upvotes: 1
Reputation: 4413
You can do to_h
on the ActionController::Parameters
. Then all permitted parameters will be in that hash:
params = ActionController::Parameters.new({
name: 'Senjougahara Hitagi',
oddity: 'Heavy stone crab'
})
params.to_h # => {}
safe_params = params.permit(:name)
safe_params.to_h # => { name: 'Senjougahara Hitagi' }
I'm no rspec pro but I think you can do:
expect(controller.params.to_h).to be({...})
Upvotes: 2