Home > Software engineering >  rspec test failed for params
rspec test failed for params

Time:03-11

i'm new to rails , i'm tring to write spec test for controller method create and I can't figure out how to pass params users to get method. here is create method for project controller

  def create
      @project = Project.new(project_params)
      @project.creator = current_user
      byebug
      if params[:project][:users].any?
        byebug
        params[:project][:users].reject!(&:empty?)
        @project.enrolled_user = User.find( params[:project][:users])
      end
    byebug
      authorize @project
      respond_to do |format|
        if @project.save
          format.html { redirect_to @project, notice: 'Project was successfully 
           created.'}
          format.json { render :show, status: :created, location: @project}
        else
          format.html { render :new}
          format.json { render json: @project.errors, status: :unprocessable_entity}
        end
      end
    end

project_spec.rb

  context "post create" do
  it "creates a new project" do
    get :new
    byebug
   
    post :create,params: { user: user.id }
    byebug
    

    expect(project1.creator).to eq(user)
    expect(enrolled_user.user_id).to eq(user1.id)
    expect(response).to be_successful
  end
end

terminal

 1) ProjectsController post create creates a new project
 Failure/Error: if params[:project][:users].any?
 
 NoMethodError:
   undefined method `[]' for nil:NilClass
 # ./app/controllers/projects_controller.rb:38:in `create'
 # ./spec/requests/project_spec.rb:49:in `block (3 levels) in <main>'

CodePudding user response:

You really need a system test rather than a controller test to achieve your requirement to test the functionality you describe here. So Rspec coupled with Capybara will allow you to do things like this

So use rails g rspec:system project and do tests like

  it "Can create a project" do
    administrator_sign_in #some system test helper that creates a user and logs a user in if needed, there are plenty of examples on how to do helpers like this.
    visit '/admin/projects'
    click_link "New" 
    #save_and_open_page #Uncomment this if you want to see what your form fields are, unstyled, can be very useful when trying to see what to fill in and what button and links to press and click
    fill_in "Name", with: "New project"
    fill_in "Other project fields", with: "Some Data"
    page.check("Name of a boolean field") #check a checkbox
    click_button("Create Project")
    project = Project.find_by name: "New project"
    expect(current_path).to eq("/admin/projects/#{project.id}")
    expect(page).to have_content("Project was successfully created")
    expect(project.name_of_boolean_field).to be true
  end

More info on generators here

More info on system tests here

More info on Capybara here

  • Related