我希望能够编写诸如
之类的规范describe Foo do
before :each do
@hash = some_very_expensive_setup_op
end
describe "hash" do
subject{@hash}
its([:a]){should == 10}
its([:b]){should == 20}
its([:c]){should == 30}
end
end
RSpec的工作方式非常合理,就是在每个其块之前执行前一个块。在许多情况下,这是你想要的,但在上面的情况下,在我的许多测试中,最终的叶子它的块正在做出没有副作用的断言。
我可以将规范重写为
describe Foo do
before :each do
@hash = some_very_expensive_setup_op
end
describe "hash" do
it "should have some attributes" do
@hash[:a].should == 10
@hash[:b].should == 20
@hash[:c].should == 30
end
end
end
现在所有断言都在一个块内完成。该规范在功能上是相同的,但我没有得到文档格式化程序中列出每个断言的第一个版本的多汁报告。
输出对我很重要,因为我尝试将输出用作web api的使用者的文档。例如,对于我的一个规格,我有一个像
这样的输出GET /status.json?ago=:ago
it should behave like authenticated
GET /status.json
accepts a valid user
rejects an invalid user
request
request attributes
:ago - number of seconds of history to calculate statistics
:current_user ( implicit )
response attributes
scale
downtime
points
nextlevel
但随着属性数量的增加,它减慢了规格。
对于细粒度报告之间的这种紧张关系是否有任何解决方案 输出和测试性能?
答案 0 :(得分:1)
您可以使用before :all
,它会在描述中的所有it
块之前运行一个给定的块。
如果您使用的是事务性功能(在Rails中是默认的),您需要小心一点。在before :all
中生成的插入内容不会被回滚,您还应该.reload
创建任何模型,以防它们被测试修改。
(为了完整性,还有一个before :suite
)
文档: https://www.relishapp.com/rspec/rspec-core/v/2-11/docs/hooks/before-and-after-hooks
答案 1 :(得分:0)
解决方案是使用https://github.com/LRDesign/rspec-steps
等软件包steps "Login and change password" do
it "should show the login form" do
visit root
page.should have_text "Login"
end
it "should successfully log in" do
fill_in :name, "Johnny User"
click "Login"
page.should have_text "Welcome, Johnny!"
end
it "should load the password change form" do
click "My Settings"
click "Update Password"
page.should have_selector("form#update_password")
end
it "should change the user's password successfully" do
fill_in :password, "foobar"
fill_in :password_confirmation, "foobar"
click "Change Password"
page.should have_text "Password changed successfully!"
User.find_by_name("Johnny User").valid_password?("foobar").should be_true
end
end
状态在它之间保持调用,如果你愿意,可以测试一系列步骤。