Repeated test descriptions with RSpec for every user role

落花浮王杯 提交于 2019-12-04 11:25:47
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's iterators in your specs. Given your particular implementation you'll have to adjust the code, but this give you the right idea for DRY'ing out your specs.

Also you'll need to make the necessary adjustments so your specs read well.

Shared 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

Shared examples can also be included in other spec files to reduce duplication. This works well in controller tests when checking authentication/authorization, which often makes for repetitive tests.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!