Logo

TODAY I LEARNED

2 posts about #testing

Test Rails log messages with RSpec

Have you wondered how to test your Rails log messages?

Try this:

it "logs a message" do
  allow(Rails.logger).to receive(:info)
  expect(Rails.logger).to receive(:info).with("Someone read this post!")

  visit root_path

  expect(page).to have_content "Welcome to TIL"
end

Or this:

it "logs a message" do
  allow(Rails.logger).to receive(:info)

  visit root_path

  expect(page).to have_content "Welcome to TIL"
  expect(Rails.logger).to have_received(:info).with("Someone read this post!")
end

Source

Learned by Victor Velazquez on Feb 18, 2021

973983 adforcodereview v3 0211021 c02 021121

Stubbing a block in rspec

There're at least two ways to stub a block in rspec, the first version is using and_yield

config = double('Config', enabled: true)
allow(app).to receive(:config).and_yield(config)
app.config do |config|
  expect(config.enabled).to be_truthy
end

The second version is receiving the block

config = double('Config', enabled: true)
allow(app).to receive(:config) do |_, &block|
  block.call(config)
end|
app.config do |config|
  expect(config.enabled).to be_truthy
end

Learned by Edwin Cruz on Feb 10, 2021

973983 adforcodereview v3 0211021 c02 021121