Any opinions which of these is better to test some query methods? I’ve been experimenting with removing the use of before, but I think in the case below, the scoped before(:all) works very well. Note, these tests are inside of an enclosing rspec describe User do
block.
Standard rspec way with many it blocks. While less concise, the context blocks explain what is being tested.
describe "find methods" do
before(:all) do # before :all only runs once in the right context
@user1 = create :user, email: "something@email.com"
@user2 = create :user, email: "jUnK@email.com"
@user3 = create :user, email: "jUnKy@email.com"
@user4 = create :user, email: "foo@bar.com"
end
describe "#by_email" do
context "no match" do
it "finds nothing" do
expect(User.by_email("JUNK")).to be_nil
end
end
context "exact match" do
it "finds user" do
expect(User.by_email(@user2.email)).to eq(@user2)
end
end
context "upcase with spaces" do
it "finds user" do
expect(User.by_email(" #{@user2.email.upcase} ")).to eq(@user2)
end
end
end
describe "#by_email_wildcard" do
context "no matches" do
it "finds no users" do
users = User.by_email_wildcard("nothing")
expect(users.size).to eq(0)
end
end
context "exact match" do
it "finds users" do
users = User.by_email_wildcard(@user1.email.upcase)
expect(users.size).to eq(1)
expect(users.first).to eq(@user1)
end
end
context "2 matches" do
it "finds 2 users" do
users = User.by_email_wildcard('jun')
expect(users.size).to eq(2)
end
end
end
end
Single it block, with single setup
describe "find methods" do
def setup_users
@user1 = create :user, email: "something@email.com"
@user2 = create :user, email: "jUnK@email.com"
@user3 = create :user, email: "jUnKy@email.com"
@user4 = create :user, email: "foo@bar.com"
end
it "finds" do
setup_users
expect(User.by_email("JUNK")).to be_nil
expect(User.by_email(@user2.email)).to eq(@user2)
expect(User.by_email(" #{@user2.email.upcase} ")).to eq(@user2)
expect(User.by_email_wildcard("nothing").size).to eq(0)
users = User.by_email_wildcard(@user1.email.upcase)
expect(users.size).to eq(1)
expect(users.first).to eq(@user1)
expect(User.by_email_wildcard('jun').size).to eq(2)
end
end