How to write shared_examples in RSpec

Category: Ruby :: Published at: 18.05.2021

We are using shared examples if we have the same assertions inside one file.

This is how we can do it:

## BEFORE

context "when user is logged in" do
      context "when current_user is requesting his own account" do
          it "is successful" do
              expect(get_show).to have_http_status(:success)
              expect(response.media_type).to eq "image/png"
          end
      end

      context "when current_user is requesting different account with permission" do
          let(:user) { create :user, access_permitted: true }

          it "is successful" do
              expect(get_show).to have_http_status(:success)
              expect(response.media_type).to eq "image/png"
          end
      end
end

## AFTER

RSpec.shared_examples "allows to download file" do
          it "is successful" do
              expect(get_show).to have_http_status(:success)
              expect(response.media_type).to eq "image/png"
          end
end

context "when user is logged in" do
      context "when current_user is requesting his own account" do
            it_behaves_like "allows to download file"
      end
end

      context "when current_user is requesting different account with permission" do
          let(:user) { create :user, access_permitted: true }

          it_behaves_like "allows to download file"
      end
end


- Click if you liked this article

Views: 73