我有一个非常丑陋的控制器规范,看起来像这样:
describe "GET index" do
context "when authorized" do
before(:each) do
sign_in @user
end
...
end
include_examples "when unauthorized"
end
describe "GET show" do
context "when authorized" do
before(:each) do
sign_in @user
end
...
end
include_examples "when unauthorized"
end
...
有没有办法将之前的过滤器和共享示例移动到每个操作的某种通用功能中?如果没有,有什么办法可以干掉它吗?
是的,你可以。一个例子来自:https://www.relishapp.com/rspec/rspec-core/docs/example-groups/shared-examples
require "set"
shared_examples "a collection object" do
describe "<<" do
it "adds objects to the end of the collection" do
collection << 1
collection << 2
expect(collection.to_a).to match_array([1, 2])
end
end
end
describe Array do
it_behaves_like "a collection object" do
let(:collection) { Array.new }
end
end
describe Set do
it_behaves_like "a collection object" do
let(:collection) { Set.new }
end
end
我应该强调,每个测试都应该只测试一件事,所以要小心你怎么写。 您还可以将共享内容移动到单独的文件,上面的链接也显示在共享内容选项卡下。
请记住,您希望测试具有可读性。 对于像之前过滤器和登录这样的小代码,我会留下。 它可能不是 DRY,但对我来说,直接阅读测试比引用单独的示例或文件更容易。 如果您有一个多次执行的大型测试,则将其移出到单独的示例或文件中会更容易。