Reputation: 12666
I have two tests that are very similar. In fact, both tests should produce the same results, but for different inputs. Each needs its own before
block but in the interest of DRY I'd like them to share the same it
block.
Is that even possible? If so, how?
Upvotes: 0
Views: 61
Reputation: 1813
Shared Examples in Rspec are designed to be used for this purpose. You can keep common it
blocks inside a shared example and include them in describe or context blocks.
Simplest example of shared_examples would be,
RSpec.shared_examples "unauthorized_response_examples" do
it { expect(subject).to respond_with(403) }
it { expect(json['message']).to eq(I18n.t("unauthorized")) }
end
And inside your controller specs whenever you need to check unauthorized response you can include examples like,
...
include_examples "unauthorized_response_examples"
Also, you can pass on parameters, action names and controller names and have before(:each|:all)
hooks and nested contexts
or describe
.
For more, you can look at rspec documentation.
Upvotes: 4
Reputation: 8688
Take the block and create and external method
for example I have some tests that require me to login to my app. So I have a helper.rb
file that I include in each spec and that contains a "login" block. Then in each test I can just call login
Upvotes: 1
Reputation: 198408
Helper methods. (Excuse the horribleness of the example. Would have been better if you'd posted yours :P)
describe "soup" do
def soup_is_salty # helper method! \o/
soup.add(:meat)
soup.add(:egg)
soup.cook
soup.salty?
end
describe "with carrot" do
before(:all) do
soup.add(:carrot)
end
it "should be salty" do
soup_is_salty # get help from helper method! \o/
end
end
describe "soup with potato" do
before(:all) do
soup.add(:potato)
end
it "should be salty" do
soup_is_salty # get help from helper method! \o/
end
end
end
Upvotes: 3