我的 Controller 规范中有很多条件和相同的期望:
if condition 1 - expect(reponse).to redirect_to same_url
if condition 2 - expect(reponse).to redirect_to same_url
if condition 3 - expect(reponse).to redirect_to same_url
RSpec 的 DRY 规则建议使用“context”而不是“if condition”。 好的,这是我的 Controller 规范:
RSpec.describe MyController, type: :controller do
describe ".method" do
context "when wrong hash" do
it "redirect to error_url" do
get :method, key: '123', hash: 'wrong_hash'
expect(subject).to redirect_to error_url
end
end
context "when status is blocked" do
it "redirect to error_url" do
get :method, key: '123', hash: valid_hash, status: 'blocked'
expect(subject).to redirect_to error_url
end
end
context "when status is expired" do
it "redirect to error_url" do
get :method, key: '123', hash: valid_hash, status: 'expired'
expect(subject).to redirect_to error_url
end
end
end
end
正如我在上面所写的,我在多种情况下都有相同的重复“它应该”和相同的期望。如何“干燥”它?
最佳答案
你想要一个共享的例子:http://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-examples
RSpec.describe MyController, type: :controller do
shared_examples "redirects to error_url" do
it "redirect to error_url" do
get(:method, path_options)
expect(subject).to redirect_to error_url
end
end
describe ".method" do
context "when wrong hash" do
let(:path_options) { {key: '123', hash: 'wrong_hash'} }
it_behaves_like "redirects to error_url"
end
# ...etc
end
end
关于ruby-on-rails - RSpec : repeated expect 的 DRY Controller 规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28887183/