What is an equivalent to database_cleaner in Rails 6? - ruby-on-rails

I have a spec, with an object and two contexts. In one context I set one key to nil and in the other not:
describe SomeClass::SomeService, type: :model do
describe '#some_method' do
subject { described_class.new(params, current_user).some_method }
mocked_params = {
min_price: 0,
max_price: 100
}
let(:params) { mocked_params }
let(:current_user) { User.create(email: 'name#mail.com') }
context 'with invalid params' do
it 'returns nil if any param is nil' do
params[:min_price] = nil
expect(subject).to eq(nil)
end
end
context 'with valid params' do
it 'returns filtered objects' do
expect(subject).to eq([])
end
end
end
end
The problem is that the second test fails because min_price is still nil.
I read that from Rails 5 on I don't need database_cleaner. Do I need it or not?
I thought that the let method creates a new object every time it sees the variable. Since I have two contexts, and the subject method is called in both of them, and inside the subject I have the variable params, why is the params object not a new one with all the fields at every context?

I read that from rails 5 on I don't need database_cleaner. Do I need
or not?
No. It's no longer needed. In previous versions of Rails the database transaction method of rolling back changes only worked (at times) with TestUnit/Minitest and fixtures.
I thought that the let method creates a new object every time it sees
the variable. Since I have two context, and the subject method is
called in both of them, and inside the subject I have the variable
params, why the params object is not a new one at every context? (with
all the fields)
This is completely wrong.
Use let to define a memoized helper method. The value will be cached
across multiple calls in the same example but not across examples.
When you do:
mocked_params = {
min_price: 0,
max_price: 100
}
let(:params) { mocked_params }
You're really just returning a reference to the object mocked_params and then mutating that object.
If you do:
let(:params) do
{
min_price: 0,
max_price: 100
}
end
You will get a new hash object on the first call to let and the value will then be cached but not shared between examples. But that's really the tip of the iceberg with this spec.
describe SomeClass::SomeService, type: :model do
describe '#some_method' do
let(:current_user) { User.create(email: 'name#mail.com') }
# explicit use of subject is a serious code smell!
let(:service) { described_class.new(params, current_user) }
context 'with invalid params' do
# since let is lazy loading we can define it in this context instead
let(:params) do
{
min_price: nil,
max_price: 100
}
end
it 'returns nil if any param is nil' do
# actually call the method under test instead of misusing subject
# this makes it much clearer to readers what you are actually testing
expect(service.some_method).to eq(nil)
end
end
context 'with valid params' do
let(:params) do
{
min_price: 0,
max_price: 100
}
end
it 'returns filtered objects' do
expect(service.some_method).to eq([])
end
end
end
end
Its also pretty questionable why the object under test takes a hash as the first positional parameter and not as the last parameter which is the Ruby way.

This happens because you initialize the mocked_params only once when the file is loaded and then you change that hash in the first test.
Instead create the params within the let block which would lead to a re-creation of the hash for each test.
Change
mocked_params = {
min_price: 0,
max_price: 100
}
let(:params) { mocked_params }
to
let(:params) do
{
min_price: 0,
max_price: 100
}
end

Related

how to test a method call once with one argument and one block in rspec

class ExternalObject
attr_accessor :external_object_attribute
def update_external_attribute(options = {})
self.external_object_attribute = [1,nil].sample
end
end
class A
attr_reader :my_attr, :external_obj
def initialize(external_obj)
#external_obj = external_obj
end
def main_method(options = {})
case options[:key]
when :my_key
self.my_private_method(:my_key) do
external_obj.update_external_attribute(reevaluate: true)
end
else
nil
end
end
private
def my_private_method(key)
old_value = key
external_object.external_object_attribute = nil
yield
external_object.external_object_attribute = old_value if external_object.external_object_attribute.nil?
end
end
I want to test following for main_method when options[:key] == :my_key:
my_private_method is called once with argument :my_key and it has a block {external_obj.update_external_attribute(reevaluate: true) } , which calls update_external_attribute on external_obj with argument reevaluate: true once.
I'm able to test my_private_method call with :my_key argument once.
expect(subject).to receive(:my_private_method).with(:my_key).once
But how do I test the remaining part of the expectation?
Thank you
It could be easier to answer your question if you post your test as well.
The setup, the execution and asseriotns/expectations.
You can find a short answer in this older question.
You can find useful to read about yield matchers.
I would suggest to mock the ExternalObject if you already haven't. But I can't tell unless you post your actual test code.
I'm going to answer your question. But, then I'm going to explain why you should not do it that way, and show you a better way.
In your test setup, you need to allow the double to yield so that the code will fall through to your block.
RSpec.describe A do
subject(:a) { described_class.new(external_obj) }
let(:external_obj) { instance_double(ExternalObject) }
describe '#main_method' do
subject(:main_method) { a.main_method(options) }
let(:options) { { key: :my_key } }
before do
allow(a).to receive(:my_private_method).and_yield
allow(external_obj).to receive(:update_external_attribute)
main_method
end
it 'does something useful' do
expect(a)
.to have_received(:my_private_method)
.with(:my_key)
.once
expect(external_obj)
.to have_received(:update_external_attribute)
.with(reevaluate: true)
.once
end
end
end
That works. The test passes. RSpec is a powerful tool. And, it will let you get away with that. But, that doesn't mean you should. Testing a private method is ALWAYS a bad idea.
Tests should only test the public interface of a class. Otherwise, you'll lock yourself into the current implementation causing the test to fail when you refactor the internal workings of the class - even if you have not changed the externally visible behavior of the object.
Here's a better approach:
RSpec.describe A do
subject(:a) { described_class.new(external_obj) }
let(:external_obj) { instance_double(ExternalObject) }
describe '#main_method' do
subject(:main_method) { a.main_method(options) }
let(:options) { { key: :my_key } }
before do
allow(external_obj).to receive(:update_external_attribute)
allow(external_obj).to receive(:external_object_attribute=)
allow(external_obj).to receive(:external_object_attribute)
main_method
end
it 'updates external attribute' do
expect(external_obj)
.to have_received(:update_external_attribute)
.with(reevaluate: true)
.once
end
end
end
Note that the expectation about the private method is gone. Now, the test is only relying on the public interface of class A and class ExternalObject.
Hope that helps.

Negating a custom RSpec matcher that contains expectations

I have a custom RSpec matcher that checks that a job is scheduled. It's used like so:
expect { subject }.to schedule_job(TestJob)
schedule_job.rb:
class ScheduleJob
include RSpec::Mocks::ExampleMethods
def initialize(job_class)
#job_class = job_class
end
...
def matches?(proc)
job = double
expect(job_class).to receive(:new).and_return job
expect(Delayed::Job).to receive(:enqueue).with(job)
proc.call
true
end
This works fine for positive matching. But it does not work for negative matching. e.g:
expect { subject }.not_to schedule_job(TestJob) #does not work
For the above to work, the matches? method needs to return false when the expectations are not met. The problem is that even if it returns false, the expectations have been created regardless and so the test fails incorrectly.
Any ideas on how to make something like this work?
I had to look for it, but I think it's nicely described here in the rspec documentation
Format (from the docs) for separate logic when using expect.not_to:
RSpec::Matchers.define :contain do |*expected|
match do |actual|
expected.all? { |e| actual.include?(e) }
end
match_when_negated do |actual|
expected.none? { |e| actual.include?(e) }
end
end
RSpec.describe [1, 2, 3] do
it { is_expected.to contain(1, 2) }
it { is_expected.not_to contain(4, 5, 6) }
# deliberate failures
it { is_expected.to contain(1, 4) }
it { is_expected.not_to contain(1, 4) }
end

A more readable request spec that changes model count

I have the following rspec request spec example which passes
it "increases count by 1" do
attributes = attributes_for(:district)
expect { post admin_districts_path, params: { district: attributes} }.to change { District.count }.by(1)
end
The expect line is a little busy, so I'm trying to break it up. The following causes an error
it "increases count by 1" do
attributes = attributes_for(:district)
block = { post admin_districts_path, params: { district: attributes} }
expect(block).to change { District.count }.by(1)
end
with error
syntax error, unexpected '}', expecting keyword_end
Why is this error happening? Is there a cleaner way to write this spec example?
I usually run into this kind of long lines in tests. Instead of creating new variables just to improve reading, what I do is to split it into different lines like this:
it "increases count by 1" do
attributes = attributes_for(:district)
expect do
post admin_districts_path, params: { district: attributes}
end.to change { District.count }.by(1)
end
Also, you can create a lambda:
block = -> { post admin_districts_path, params: { district: attributes} }
expect(block).to change { District.count }.by(1)
I prefer to create a little helper method within the relevant describe block. This is taken from a sample rails request spec, and I'm assuming you have FactoryBot set up. Something like this:
describe "create /district" do
def create_district_request
#district = build(:district)
params = {district: {name: #district.name etc.}}
post district_path, params: params
end
it "creates a district" do
expect {create_district_request}.to change{District.count}.by(1)
end
end
Hope it helps.

Test service Rspec always return empty array

My service work perfectly testing manually, but I need write service test. So I create service test in rspec
require 'rails_helper'
RSpec.describe ReadService do
describe '#read' do
context 'with 4 count' do
let!(:object1) { create(:obj) }
let!(:object2) { create(:obj) }
let!(:object3) { create(:obj) }
let!(:object4) { create(:obj) }
it 'return 2 oldest obj' do
expect(ReadService::read(2)).to eq [report4,report3]
end
end
But ReadService::read(2) in test return []
When I type this manually
ReadService::read(2)
it return array with two oldest obj correctly. What do I wrong? I call this service in test not correctly ?
ReadService implementation
class ReadService
def self.read(count)
objects = Object.get_oldest(count)
objects.to_a
end
end
This happens because you use let!. This helper will only create the object when you first reference it, which you never do in your test. In this case you should rather use a before :each or before :all block (depending on what your specs do in the describe block):
before :each do
#object1 = create :obj
#object2 = create :obj
#object3 = create :obj
#object4 = create :obj
end
If you do not need a reference to the objects, you can create them in a loop:
4.times { create :obj }

Test that method has a default value for an argument with RSpec

How can I test that a method that takes an argument uses a default value if an argument is not provided?
Example
# this method shouldn't error out
# if `Post.page_results` without a parameter
class Post
def self.page_results(page=1)
page_size = 10
start = (page - 1) * page_size
finish = start + page_size
return Page.all[start..finish]
end
end
How do I check in rspec that page equals 1 if page_results is called without argument?
Testing that the page param has the default value set, is most likely not what you should test. In most cases, it is better to test the behaviour instead of the implementation (Talk from Sandy Metz about testing). In your case, you should test if the expected set of Pages is returned, when page_results is called without params (default case).
Here is an example of how you could do this:
describe Post do
describe ".page_results" do
context "when Pages exist" do
subject(:pages) { described_class.page_results(page) }
let(:expected_pages_default) { expected_pages_page_1 }
let(:expected_pages_page_1) { Page.all[0..10] }
let(:expected_pages_page_2) { Page.all[10..20] }
before do
# Create Pages
end
context "when no page param is give " do
# HINT: You need to redefine subject in this case. Setting page to nil would be wrong
subject(:pages) { described_class.page_results }
it { expect(pages).to eq expected_pages_default }
end
context "when the page param is 1" do
let(:page) { 1 }
it { expect(pages).to eq expected_pages_page_1 }
end
context "when the page param is 2" do
let(:page) { 2 }
it { expect(pages).to eq expected_pages_page_2 }
end
end
context "when no Pages exist" do
# ...
end
end
end
describe Post do
describe '#page_results' do
let(:post) { create :post }
context 'without arguments' do
it { post.page_results.should eq 1 }
end
end
end
The create :post statement is how you would do it with FactoryGirl. But you could of course mock or stub out your model.
Update
describe Post do
describe '#page_results' do
context 'without arguments' do
it { Post.page_results.should eq 1 }
end
context 'with arguments' do
it { Post.page_results('foo').should eq 'bar' }
end
end
end
I use before_validation to set defaults e.g
before_validation do
self.some_attribute ||=a_default_value
end
That leaves open the possibility to override the default
SomeClassWithDefaultAttributes.create(some_attribute:a_non_default_value)
Keep in mind that if #before_validation returns false, then the validation will fail

Resources