If you want to mock a method in RSpec, you should use the allow method for mock and the singleton method.

Overview

In rspec, you often want to mock a method to make it easier to test.

In the example below, the set_complex_config method affects the ʻadmin?` method.

The set_complex_config method already has its own test code and we only want the response.

#Code example is appropriate
class User
  def admin?
    res = set_complex_config
    case res
    when 'hoge'
      'hoge'
    when 'fuga'
      'fuga'
    end
  end

  def set_complex_config
    #Complex processing
  end
end

I can think of two ways to mock in such a case, so I thought about which one was better.

How to mock

① Define a singleton method and mock

How to overwrite the set_complex_config method of User class with singleton method as shown below.

let(:hoge_let) { 'hoge' }
it do
  user = create(:user)
  hoge_var = 'hoge'
  user.define_singleton_method(:set_complex_config) { hoge_var }
  user.set_complex_config =>Move

  user.define_singleton_method(:set_complex_config) { hoge_let }
  user.set_complex_config => wrong number of arguments (given 0, expected 2..3)
end

At first glance, it looks cool, but in this case, inside the example or before block, the block of the define_singleton_method method can't read the let variable.

② Mock with allow method

The allow method works fine.

let(:hoge_let) { 'hoge' }
it do
  user = create(:user)
  allow(user).to receive(:attributes).and_return(hoge_let)
  user.set_complex_config =>Move
end

Conclusion

It seems better to use ʻallow (). To receive (). And_return ()` obediently.

Recommended Posts

If you want to mock a method in RSpec, you should use the allow method for mock and the singleton method.
When you want to use the method outside
You may not want to use the remove method in ArrayList very often
If you want to recreate the instance in cloud9
I want to call a method and count the number
If you want to include the parent class in Lombok's @builder
[Swift] When you want to know if the number of characters in a String matches a certain number ...
[For super beginners] The minimum knowledge you want to keep in mind with hashes and symbols
How to test a private method in Java and partially mock that method
[Swift] If you want to use a URL that includes Japanese, use addingPercentEncoding.
I want you to use Enum # name () for the Key of SharedPreference
[RSpec] When you want to use the instance variable of the controller in the test [assigns is not recommended]
If it is Ruby, it is efficient to make it a method and stock the processing.
If you want to satisfy the test coverage of private methods in JUnit
If you are using Android Room and want to change the column definition
I want you to use Scala as Better Java for the time being
Do you use the for statement after all? Do you use a while statement? Proper use of for statement and while statement
Rspec: I want to test the post-execution state when I set a method on subject
For those who want to use MySQL for the database in the environment construction of Rails6 ~.
I want to use a little icon in Rails
If you want to use Mockito with Kotlin, use mockito-kotlin
[Ruby] When you want to assign the result obtained by conditional branching to a variable and put it in the argument
How to mock a super method call in PowerMock
I want to use PowerMock in a class that combines parameterized tests and ordinary tests
I want to click a GoogleMap pin in RSpec
Use a binary search to see if there are any values in the array
If hash [: a] [: b] [: c] = 0 in Ruby, I want you to extend it recursively even if the key does not exist.
What to do if you select a JRE in Eclipse and get "The selected JRE does not support the current compliance level 11"
If you want to make a Java application a Docker image, it is convenient to use jib.
Use JLine when you want to handle keystrokes on the console character by character in Java
How to use the getter / setter method (in object orientation)
What to do if you get a java.io.IOException in GlassFish
How to create a placeholder part to use in the IN clause
Create a method to return the tax rate in Java
I want to use the sanitize method other than View.
What to do if you can't use the rails command
Mock and stub in RSpec
A memorandum when you want to see the data acquired by Jena & SPARQL for each variable.
What to do if you get a "Mysql2 :: Error: Operand should contain 1 column (s)" error in Rails
[Java] How to search for a value in an array (or list) with the contains method
What to do when you want to know the source position where the method is defined in binding.pry
If you just want to run your containers in the cloud, Azure Container Instances is easy
In order not to confuse the understanding of getters and setters, [Do not use accessors for anything! ]
I want to create a chat screen for the Swift chat app!
What to do if you get a gcc error in Docker
[PostgreSQL] If you want to delete the Rails app, delete the database first!
Use Modifier # isStatic to determine if the [Reflection] method is static.
If you want to change the Java development environment from Eclipse
Why you should add the Override annotation when overriding a method
What to do if you get a DISPLAY error in gym.render ()
How to store the information entered in textarea in a variable in the method
What to do if you forget the root password in CentOS7
How to use the link_to method
Creating an ArrayList that allows you to throw in and retrieve the coordinates of a two-dimensional plane
How to use the include? method
How to use the form_with method
[For beginners] I want to automatically enter pre-registered data in the input form with a selection command.
What to do if you can't bundle update and bundle install after installing Ruby 3.0.0 in the Rails tutorial
What to do if Operation not permitted is displayed when you execute a command in the terminal
[Rails + Webpacker] I want to use images of assets! Until you can view the image in Vue.js
If you want to step up Ruby → Udemy "Introduction to Ruby on Rails for the first time-Learn Ruby and Rails from the basics and publish your web application online"