Ruby Rspec:积极和消极案例的干燥共享示例
使用RSpec,我如何编写一组干燥的、可用于正面和负面案例的共享示例 适用于积极案例的共享示例:Ruby Rspec:积极和消极案例的干燥共享示例,ruby,unit-testing,rspec,Ruby,Unit Testing,Rspec,使用RSpec,我如何编写一组干燥的、可用于正面和负面案例的共享示例 适用于积极案例的共享示例: shared_examples "group1" do it "can view a person's private info" do @ability.should be_able_to(:view_private_info, person) end # also imagine I have many other examples of positive cases her
shared_examples "group1" do
it "can view a person's private info" do
@ability.should be_able_to(:view_private_info, person)
end
# also imagine I have many other examples of positive cases here
end
如果有与
相反的东西,比如它应该表现得像,比如它不应该表现得像,那就太好了。我理解示例的文本必须灵活。您可以这样做:
测试类别:
class Hat
def goes_on_your_head?
true
end
def is_good_to_eat?
false
end
end
class CreamPie
def goes_on_your_head?
false
end
def is_good_to_eat?
true
end
end
示例:
shared_examples "a hat or cream pie" do
it "#{is_more_like_a_hat? ? "goes" : "doesn't go" } on your head" do
expect(described_class.new.goes_on_your_head?).to eq(is_more_like_a_hat?)
end
it "#{is_more_like_a_hat? ? "isn't" : "is" } good to eat" do
expect(described_class.new.is_good_to_eat?).to eq(!is_more_like_a_hat?)
end
end
describe Hat do
it_behaves_like "a hat or cream pie" do
let(:is_more_like_a_hat?) { true }
end
end
describe CreamPie do
it_behaves_like "a hat or cream pie" do
let(:is_more_like_a_hat?) { false }
end
end
我不太可能在实际代码中这样做,因为很难编写可理解的示例描述。相反,我将制作两个共享示例,并将复制提取到方法中:
def should_go_on_your_head(should_or_shouldnt)
expect(described_class.new.goes_on_your_head?).to eq(should_or_shouldnt)
end
def should_be_good_to_eat(should_or_shouldnt)
expect(described_class.new.is_good_to_eat?).to eq(should_or_shouldnt)
end
shared_examples "a hat" do
it "goes on your head" do
should_go_on_your_head true
end
it "isn't good to eat" do
should_be_good_to_eat false
end
end
shared_examples "a cream pie" do
it "doesn't go on your head" do
should_go_on_your_head false
end
it "is good to eat" do
should_be_good_to_eat true
end
end
describe Hat do
it_behaves_like "a hat"
end
describe CreamPie do
it_behaves_like "a cream pie"
end
当然,我不会提取这些方法,甚至根本不会使用共享示例,除非实际示例足够复杂,足以证明它的合理性。我已经想了好几个月了。我认为这是不可能的,但也许这是最好的。规格可能很难遵循。