我在Rails中有三个页面都显示相同的标题,因此需要完全相同的集成测试。
不是重复自己并编写看起来几乎完全相同的单独测试,这里最好的方法是什么?我已经尝试将共享断言放入模块中,但尚未成功将其加载到每个测试场景中。
UNDRY:
class IntegrationTest
describe "page one" do
before { visit page_one_path }
it "should have a home page link" do
page.find_link "Home"
end
end
describe "page two" do
before { visit page_two_path }
it "should have a home page link" do
page.find_link "Home"
end
end
describe "page three" do
before { visit page_three_path }
it "should have a home page link" do
page.find_link "Home"
end
end
end
尝试将其烘干失败......
模块:
/lib/tests/shared_test.rb
module SharedTest
def test_header
it "should have a home page link" do
page.find_link "Home"
end
end
end
测试:
class IntegrationTest
include SharedTest
describe "page one" do
before { visit page_one_path }
test_header
end
describe "page two" do
before { visit page_two_path }
test_header
end
describe "page three" do
before { visit page_three_path }
test_header
end
end
我还没有弄清楚如何编写模块,所以毫无疑问这不起作用。有人能指出我正确的方向吗?
答案 0 :(得分:4)
在使用Minitest规范DSL时,在不同describe
块之间共享测试的方法是将模块包含在您希望运行这些测试的每个describe
块中。
module SharedTest
def test_header
assert_link "Home"
end
end
class IntegrationTest < ActiveDispatch::IntegrationTest
describe "page one" do
include SharedTest
before { visit page_one_path }
end
describe "page two" do
include SharedTest
before { visit page_two_path }
end
describe "page three" do
include SharedTest
before { visit page_three_path }
end
end
Minitest的Test API与Minitest Spec DSL的不同之处在于它们在继承时的行为方式。请考虑以下事项:
class PageOneTest < ActiveDispatch::IntegrationTest
def setup
visit page_one_path
end
def test_header
assert_link "Home"
end
end
class PageTwoTest < PageOneTest
def setup
visit page_two_path
end
end
class PageThreeTest < PageOneTest
def setup
visit page_three_path
end
end
PageTwoTest和PageThreeTest测试类继承自PageOneTest,因此它们都具有test_header
方法。 Minitest将运行所有三项测试。但是,当使用规范DSL实现时,test_header
方法不会被继承。
class PageOneTest < ActiveDispatch::IntegrationTest
def setup
visit page_one_path
end
def test_header
assert_link "Home"
end
describe "page two" do
before { visit page_two_path }
end
describe "page three" do
before { visit page_three_path }
end
end
在这种情况下,只运行一个测试。由describe "page two"
创建的测试类将继承自PageOneTest,但将删除所有测试方法。为什么?因为Minitest的规范DSL基于RSpec,这就是RSpec的工作方式。 Minitest竭力克服使用规范DSL时继承的测试方法。因此,在使用规范DSL时共享测试的唯一方法是将模块包含在您希望它们所在的每个describe
块中。所有其他非测试方法,包括before
和after
挂钩,以及let
访问器,将被继承
答案 1 :(得分:0)
这是使用MiniTest的DSL规范时重用测试的一种干净方法-在函数中定义测试,然后在要包含测试的位置调用该函数。
示例:
def include_shared_header_tests
it "should be longer than 5 characters" do
assert subject.length > 5
end
it "should have at least one capital letter" do
assert /[A-Z]/ =~ subject
end
end
# This block will pass
describe "A good header" end
subject { "I'm a great header!" }
include_shared_header_tests
end
# This block will fail
describe "A bad header" end
subject { "bad" }
include_shared_header_tests
end