kon*_*yak 5 ruby unit-testing rspec
使用RSpec,如何编写一组DRY的shared_examples,可以用于正面和负面的情况?
适用于肯定案例的shared_examples示例:
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
Run Code Online (Sandbox Code Playgroud)
如果有一些相对的it_should_behave_like,比如it_should_not_behave_like,那简直太好了.我理解示例的文本必须是灵活的.
你可以这样做:
正在测试的类:
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
Run Code Online (Sandbox Code Playgroud)
例子:
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
Run Code Online (Sandbox Code Playgroud)
我不太可能在实际代码中这样做,因为很难编写可理解的示例描述。相反,我会制作两个共享示例并将重复项提取到方法中:
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
Run Code Online (Sandbox Code Playgroud)
当然,我不会提取这些方法,甚至根本不会使用共享示例,除非实际示例足够复杂以证明其合理性。