I don't understand why I run expect before the code I want to test when I use the mock in RSpec.

Asked 2 years ago, Updated 2 years ago, 91 views

I created the test code below, but if I put the code expect under get:index params, I get an error if there is no value.
It's strange that other test codes (without a mock) had code that you wanted to test above expect and the code that you want to test with expect was executed to get the value.
Could you please take a look at the details?
Thank you for your cooperation.

Error Contents

Failure/Error: @[email protected] (params[:term])
       # <InstanceDouble (Project) (anonymous) > received unexpected message: notes with (no args)

Test Code

require 'rails_helper'

RSpec.describe NotesController, type::controller do
  let(:user) {double("user")}
  # Become responsive to project_owner, project_id
  let(:project) { instance_double("Project", owner:user, id:"123")}

  before do
    # Specify an instance with a method that you want to stub to allow
    # Specify the symbol of the method you want to stub to receive.
    # Specify the value it will return.
    allow(request.env ["warden"]).
      to receive(:authenticate!).and_return(user)
    allow (controller)
      to receive(:current_user).and_return(user)
    allow (Project)
      to receive(:find).with("123").and_return(project)
  end
  describe "#index" do
    # Search for notes by keywords entered
    it "search notes by the provided keyword" do
      # For reference, allow used with allow is used in it.
      # The argument that becomes a chain like project.notes.search is 'rorate tires'
      # This expect must be added before the app can run before the test passes, called no args
      # I don't know if it's the image of putting up a mock first and accessing it.
      expect(project).to receive_message_chain(:notes,:search).with("rotate tires")
      get —index,
        param: {project_id:project.id, term: "rotate tires"}
    end
  end
end

ruby-on-rails ruby rspec mock

2022-09-30 19:42

1 Answers

It is called a spy and monitors the processing after performing the processing that you want to test, so you can check the contents.
I think it looks like this.

Reference

Understand RSpec Spy


2022-09-30 19:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.