controller specs
This is an article about.
When I defined the variables for commonality, I decided to keep it as a memorandum because it got swamped if I named it properly!
ruby 2.6.5 rails 5.2.4.2 rspec 3.7 capybara 2.15 factory_bot_rails 4.11
spec/controllers/posts_controller_spec.rb
require 'rails_helper'
RSpec.describe PostsController, type: :controller do
context "Actions that do not require login" do
.
.
.
end
context "Actions that require login" do
let(:user) { FactoryBot.create(:user) }
let(:login_user) { login(user) }
let(:post) { FactoryBot.create(:post) }
let(:post_params) { FactoryBot.attributes_for(:post) }
describe "create action" do
context "For logged-in users" do
it "Create a post" do
login user
expect {
post :create, params: { post: post_params }
}.to change(user.posts, :count).by(1)
end
end
context "For users who are not logged in" do
.
.
.
end
end
end
end
Premise ➡︎ I'm using FactoryBot to create test data. (Post is associated) ➡︎ The login (user) method is defined in the rails_helper.rb file for login.
Failures:
1)PostsController Actions that require login create Action For logged-in users Create a post
Failure/Error: post :create, { post: post_params }
ArgumentError:
wrong number of arguments (given 2, expected 0)
# ./spec/controllers/posts_controller_spec.rb:85:in `block (5 levels) in <main>'
The number of arguments on the caller (give) is 2, and the number of arguments on the method side (expected) is 0.
In other words, I am angry that "two arguments are called, but there is no corresponding argument on the method side".
post :create, params: { post: post_params }
The reason why this description causes an error is that the above "post: ``
" part that I was supposed to pass as the `parameter key`
is actually the key. It was caused by `, which was considered to be a
`` post variable, which was defined to make posts common, not as.
The two gaves meant "
post:` "and"
post_params``` "...
So, I will change the naming of the `post variable" of the commoner so that the "post:" part can be recognized as a key.
```
spec/controllers/posts_controller_spec.rb
require 'rails_helper'
RSpec.describe PostsController, type: :controller do
context "Actions that require login" do
let(:user) { FactoryBot.create(:user) }
let(:login_user) { login(user) }
- let(:post) { FactoryBot.create(:post) } #Delete
+ let(:new_post) { FactoryBot.create(:post) } #Variable name change
let(:post_params) { FactoryBot.attributes_for(:post) }
describe "create action" do
context "For logged-in users" do
it "Create a post" do
login user
expect {
post :create, params: { post: post_params }
}.to change(user.posts, :count).by(1)
end
end
end
end
end
Rewrite the post variable to the new_post variable.
$ bin/rspec spec/controllers
1 examples, 0 failures
I passed!
This error made me feel like I should be careful when naming variables ... lol
https://qiita.com/yikegaya/items/98f0c12f5c25ee4731a1
Recommended Posts