我使用的是Ruby on Rails 3.1.0和rspec-rails 2 gem。我想在我的规范文件中重构以下示例代码:
describe "Making things" do
it "should make a thing" do
# Make the thing
...
# This is the same statement as that present in the "should make another
# thing" example (read below for more information)
response.body.should include("Hello World")
end
it "should make another thing" do
# Make another thing
...
# The same statement as that present in the "should make a thing" example
response.body.should include("Hello World")
end
end我如何重构上面的response.body.should include("Hello World")代码,以便编写更少的代码?也就是说,如何使用一个对两个规范示例都有效的语句来测试response.body内容?
发布于 2011-09-28 21:19:14
使用shared_examples_for。
如下所示:
describe "Making things" do
before do
@user.new
end
shared_examples_for "normal case" do
it "shows hello world" do
response.body.should include("Hello World")
end
# more tests could be here
end
context "making a thing" do
before(:each) do
# make thing
end
it_should_behave_like_a "normal case"
end
context "making another thing" do
before(:each) do
# make another thing
end
it_should_behave_like_a "normal case"
end
end请参阅文档here。
https://stackoverflow.com/questions/7583768
复制相似问题