多次想通过同一个操作检查多个内容,比如我想执行 PUT 并查看请求是否返回 200、响应值是否包含某些值以及
ActiveRecord
模型是否已更新。
在下一个示例中,我尝试使用
before
但它在每个 it
之前运行。
context "with valid params" do
before do
put my_url
end
it "returns a 200 response" do
expect(response).to have_http_status(200)
end
it "updates the right values" do
expect(my_model.min_area).to eq(111)
expect(my_model.max_area).to eq(222)
end
it "dont update a param if it is not sent" do
expect(my_model.budget).to eq(333)
end
end
我希望
before
块只运行 1 次,并且每次都会验证它的内容。
通过这种方法,当失败时我可以清楚地看到失败的地方。
另一种方法是删除每个
it
并只保留 1 个:
context "with valid params" do
it "updates all" do
put my_url
expect(response).to have_http_status(200)
expect(my_model.min_area).to eq(111)
expect(my_model.max_area).to eq(222)
expect(my_model.budget).to eq(333)
end
end
但是这种方法在失败时并不能立即告诉我什么失败了。
如何才能做到这一点,而不必为每个
before
块执行 it
?
你可以这样做而不是
before(:context)
context "with valid params" do
it "updates all" do
put my_url
expect(response).to have_http_status(200)
expect(my_model.min_area).to eq(111)
expect(my_model.max_area).to eq(222)
expect(my_model.budget).to eq(333)
end
end
但是你需要的是告诉 RSpec 聚合故障
你可以做每个区块
context "with valid params", :aggregate_failures do
it "updates all" do
put my_url
expect(response).to have_http_status(200)
expect(my_model.min_area).to eq(111)
expect(my_model.max_area).to eq(222)
expect(my_model.budget).to eq(333)
end
end
或者为您的项目设置全局,还有其他选项可用,选择您最喜欢的。
before(:context)
。
before(:context) do
put my_url
end
context "with valid params" do
it "returns a 200 response" do
expect(response).to have_http_status(200)
end
it "updates the right values" do
expect(my_model.min_area).to eq(111)
expect(my_model.max_area).to eq(222)
end
it "dont update a param if it is not sent" do
expect(my_model.budget).to eq(333)
end
end
请注意,有些人可能会认为使用
before(:context)
是一种 反模式。