context "Generate user" do
subject { User.create(name: "John") }
it "One user is generated" do
is_expected.to change(User.count).by(1)
end
end
As subject, I defined a method for user generation. In this situation, I sometimes wanted to test with the same subject that the generated username was "John".
it "Username is John" do
subject
expect(User.last.name).to eq("John")
end
Even so, I got an error saying that User.last is nil, and it seems that the contents of the subject are not being executed.
puts subject.class
If you look up the class as
Proc
Will be returned.
In ruby, there is a class called Proc class that stores the execution code itself in a variable.
Therefore
subject
Even if you write as
"String"
It's the same as writing, and nothing happens. Therefore, it is necessary to execute it as an object of Proc class.
There are various ways to do it, but for example
subject.call
there is
Therefore
it "Username is John" do
subject.call
expect(User.last.name).to eq("John")
end
This passed.
It may be in a different context, or the subject setting may not be good, but if you face the same situation, please consider it.
context "Generate user" do
subject { User.create(name: "John") }
it "One user is generated" do
is_expected.to change(User.count).by(1)
end
it "Username is John" do
subject.call
expect(User.last.name).to eq("John")
end
end
that's all.
Recommended Posts