Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 430
CodeSmith Avatar asked May 23 '26 00:05

CodeSmith


2 Answers

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
like image 138
ascherman Avatar answered May 24 '26 17:05

ascherman


Also, you can create a lambda:

block = -> { post admin_districts_path, params: { district: attributes} }
expect(block).to change { District.count }.by(1)
like image 23
Ilya Avatar answered May 24 '26 18:05

Ilya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!