A story I was addicted to with implicit type conversion of ActiveRecord during unit testing

Event

The following unit test code fails.

item_spec.rb


    it 'Only half-width numbers can be saved' do
      @item.price = '1000'
      @item.valid?
      expect(@item.errors.full_messages).to include('Price Half-width characters.')
    end

Cause

When assigning the character string "1000" to the integer type item "price", Implicit type conversion was done and the price was assigned the number "0".

↓ Check how implicit type conversion is performed on the console ↓

irb(main):002:0> @item.price = '1000'
=> "1000"
irb(main):003:0> @item.price
=> 0

After substituting the character string "1000", the price value will be the numerical value "0".

This is due to a feature called "ActiveRecord Attributes API" added in Rails 5. Implicit type conversion is an image in which the following setter is moving behind the scenes. The point is to_i.

  #Setter
  def price=(price)
    @price = price.to_i
  end

Conclusion

Solved by writing the following in the Item model

item.rb


class Item < ApplicationRecord
  attr_accessor :price

[Explanation] attr_accessor is a method that can realize setter / getter processing for items. The following description and "attr_accessor: price" have the same meaning.

  #Setter
  def price=(price)
    @price = price
  end

  #Getter
  def price
    @price
  end

That is, by calling a pure setter (not to_i) with this You will be able to assign a string that is not to_i to price.

irb(main):002:0> @item.price = '1000'
=> "1000"
irb(main):003:0> @item.price
=> "1000"

[Reference link]

For the mechanism of "Active Record Attributes API", I referred to the following article. https://www.wantedly.com/companies/wantedly/post_articles/31132

Recommended Posts

A story I was addicted to with implicit type conversion of ActiveRecord during unit testing
A story I was addicted to when testing the API using MockMVC
I was addicted to unit testing with the buffer operator in RxJava
A story that I was addicted to twice with the automatic startup setting of Tomcat 8 on CentOS 8
A story I was addicted to in Rails validation settings
A story addicted to toString () of Interface proxied with JdkDynamicAopProxy
[Circle CI] A story I was addicted to at Start Building
I was addicted to a simple test of Jedis (Java-> Redis library)
A story addicted to EntityNotFoundException of getOne of JpaRepository
I was addicted to doing onActivityResult () with DialogFragment
I was addicted to the record of the associated model
GetXxxx of ResultSet was addicted to primitive type (Java)
What I was addicted to when developing a Spring Boot application with VS Code
A memo that I was addicted to when making batch processing with Spring Boot
A memorandum because I was addicted to the setting of the Android project of IntelliJ IDEA
A story I was addicted to when getting a key that was automatically tried on MyBatis
I was addicted to setting default_url_options with Rails devise introduction
I want to make a specific model of ActiveRecord ReadOnly
kintone clone? I was quite addicted to launching OSS WebDB Extension with Lightsail + Docker, so make a note of it.
A story I was addicted to before building a Ruby and Rails environment using Ubuntu (20.04.1 LTS)
I was addicted to the setting of laradock + VSCode + xdebug
What I was addicted to with the Redmine REST API
The story I was addicted to when setting up STS
A story that I struggled to challenge a competition professional with Java
A story of connecting to a CentOS 8 server with an old Ansible
A note when I was addicted to converting Ubuntu on WSL1 to WSL2
What I was addicted to when implementing google authentication with rails
I was addicted to the API version min23 setting of registerTorchCallback
I was addicted to starting sbt
The story of making it possible to build a project that was built by Maven with Ant
A story that I wanted to write a process equivalent to a while statement with the Stream API of Java8
Recorded because I was addicted to the standard input of the Scanner class
I was a little addicted to running old Ruby environment and old Rails
[CircleCI] I was addicted to the automatic test of CircleCI (rails + mysql) [Memo]
I was a little addicted to ssh connection from mac to linux (ubuntu)
A story addicted to JDBC Template placeholders
I want to write a unit test!
I was addicted to rewriting to @SpringApplicationConfiguration-> @SpringBootTest
I was addicted to the roll method
I was addicted to the Spring-Batch test
I tried to implement a function equivalent to Felica Lite with HCE-F of Android
I was a little addicted to the S3 Checksum comparison, so I made a note.
Rails6 I want to make an array of values with a check box
I tried to clone a web application full of bugs with Spring Boot
A story that I was really into when I did triple DES with ruby
I was addicted to using RXTX on Sierra
I tried to break a block with java (1)
[Jackson] A story about converting the return value of BigDecimal type with a custom serializer.
When I tried to unit test with IntelliJ, I was told "java.lang.OutOfMemoryError: Java heap space"
The part I was addicted to in "Introduction to Ajax in Java Web Applications" of NetBeans
What I was addicted to when trying to properly openAPI/Swagger documentation with Rails + Grape + Grape Swagger
Java: A story that made me feel uncomfortable when I was taught to compare strings with equals for no reason.