Repeated test descriptions with RSpec for each user role

Creating some controller tests using RSpec, I find myself repeating a few test cases for every possible user role.

for instance

describe "GET 'index'" do context "for admin user" do login_user("admin") it "has the right title" do response.should have_selector("title", :content => "the title") end end context "for regular user" do login_user("user") it "has the right title" do response.should have_selector("title", :content => "the title") end end end 

This is a simple example to express my point of view, but I have many tests that are repeated ... Of course, there are also some tests that are unique for each context, but it doesnโ€™t matter here.

Is there a way to write tests only once and then run them in different contexts?

+4
source share
3 answers
 describe "GET 'index'" do User::ROLES.each do |role| context "for #{role} user" do login_user(role) it "has the right title" do response.should have_selector("title", :content => "the title") end end end end 

You can use ruby โ€‹โ€‹iterators in your specifications. Given your specific implementation, you will have to adjust the code, but this gives you the right idea for DRY's from your specifications.

You will also need to make the necessary adjustments to make your specifications readable.

+2
source

Common examples are a more flexible approach to this:

 shared_examples_for "titled" do it "has the right title" do response.should have_selector("title", :content => "the title") end end 

And in the example

 describe "GET 'index'" do context "for admin user" do login_user("admin") it_behaves_like "titled" end end 

General examples can also be included in other specification files to reduce duplication. This works well in controller tests for authentication / authorization, which often makes repeated tests.

+14
source

Source: https://habr.com/ru/post/1335418/


All Articles