我有一个非常丑陋的 Controller 规范,看起来像这样:
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
我要强调的是,每个测试都应该只测试一件事,所以要小心你的编写方式。您还可以将共享内容移动到单独的文件,上面的链接也在共享内容选项卡下显示。
请记住,您希望测试具有可读性。对于像 before 过滤器和登录这样的小代码,我保留了下来。它可能不是 DRY,但对我来说,直接阅读测试比引用单独的示例或文件更容易。如果您有一个需要多次执行的大型测试,将其移出到单独的示例或文件中会更容易。
关于ruby-on-rails - 如何在多个 RSpec 上下文中使用相同的共享示例和前置过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20979123/