Skip to content

expect(CreatesProject).to have_received(:new).with({name: "Runway", task_string: "start something:2"}) #63

@MunimIftikhar

Description

@MunimIftikhar

I am trying to run the controller test in the Rails application.

Controller code

Here is the code I'm trying to test (/app/controllers/projects_controller.rb):

class ProjectsController < ApplicationController
  ## START: show
  def show
    @project = Project.find(params[:id])
    respond_to do |format|
      format.html {}
      format.js { render json: @project.as_json(root: true, include: :tasks) }
    end
  end
  ## END: show

  def new
    @project = Project.new
  end

  def index
    @projects = Project.all
  end

  ## START: create
  def create
    @workflow = CreatesProject.new(
      name: params[:project][:name],
      task_string: params[:project][:tasks])
    @workflow.create
    if @workflow.success?
      redirect_to projects_path
    else
      @project = @workflow.project
      render :new
    end
  end
  ## END: create
end

Controller Test

Here is the test(/spec/controllers/projects_controller_spec):

require "rails_helper"

RSpec.describe ProjectsController, type: :controller do

  describe "create" do
    it "calls the workflow with parameters" do
      workflow = instance_spy(CreatesProject, success?: true)
      allow(CreatesProject).to receive(:new).and_return(workflow)
      post :create,
        params: {project: {name: "Runway", tasks: "start something:2"}}
      expect(CreatesProject).to have_received(:new)
        .with({name: "Runway", task_string: "start something:2"})
    end

  end

end

Error

After running the command bundle exec rspec, I'm getting the following error:

1) ProjectsController create calls the workflow with parameters
     Failure/Error:
       expect(CreatesProject).to have_received(:new)
         .with({name: "Runway", task_string: "start something:2"})
     
       (CreatesProject (class)).new({:name=>"Runway", :task_string=>"start something:2"})
           expected: 1 time with arguments: ({:name=>"Runway", :task_string=>"start something:2"})
           received: 0 times
     # ./spec/controllers/projects_controller_spec.rb:11:in `block (3 levels) in <top (required)>'

Can anyone help me with this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions