如何重用示例,以便只覆盖嵌套上下文的细节?
类似这样的事情(我使用 thee
而不是它,这表明它是在嵌套上下文中执行的。它不在 RSpec 中,正是我想要的):
describe "Abilities" do
subject { Abilities.new user }
context "allowed" do
let(:user) { Factory(:power_user) }
thee { should be_able_to :create, object }
thee { should be_able_to :read, object }
thee { should be_able_to :update, object }
context "comment" do
let(:object) { Factory(:comment) }
end
context "post" do
let(:object) { Factory(:post) }
end
context "blog" do
let(:object) { Factory(:blog) }
end
end
end
此示例最终会针对 3 个上下文(评论、帖子、博客)生成 3 个示例(创建、阅读、更新),从而导致总共 9 个示例。
如何实现它(不编写共享示例)?
最佳答案
没有办法继承例子,但你可以创建一个类方法:
describe "Abilities" do
subject { Abilities.new user }
def self.should_allow_stuff
it { should be_able_to :create, object }
it { should be_able_to :read, object }
it { should be_able_to :update, object }
end
context "allowed" do
let(:user) { Factory(:power_user) }
context "comment" do
let(:object) { Factory(:comment) }
should_allow_stuff
end
context "post" do
let(:object) { Factory(:post) }
should_allow_stuff
end
context "blog" do
let(:object) { Factory(:blog) }
should_allow_stuff
end
end
end
如果需要,您可以根据需要进行重构。
关于ruby-on-rails - 在嵌套 Rspec 上下文中继承示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7829901/