[英]RSpec: How can I make one shared_example test that tests many different controller PATCH requests that all update different attributes?
I have various controllers and I have tests for each one that test their update action. 我有各种控制器,并且每个控制器都有测试其更新操作的测试。 The tests have all the exact same structure: it tests if it a patch request will update and change the object, or not. 测试具有完全相同的结构:它测试修补程序请求是否会更新和更改对象。 The only difference between these tests are which attribute the tests check to see for its change assertion. 这些测试之间的唯一区别是测试检查哪个属性以查看其更改断言。 These attributes are unique to the controllers. 这些属性是控制器唯一的。
class CarsController
def update
# update attribute
...
end
end
and 和
class DogsController
def update
# update attribute
...
end
end
My tests (2 of many more): 我的测试(还有2个测试):
CarsSpec
describe "PATCH" do
it "should update the car" do
expect do
patch :update, id: object.id, data: {make: "honda"}
end.to change {object.reload.make}
end
end
DogSpec
describe "PATCH" do
it "should update the dog" do
expect do
patch :update, id: object.id, data: {breed: "husky"}
end.to change {object.reload.breed}
end
end
As you can see, they're the exact same structure of tests so naturally, to be DRY I want to extract them into a shared_example to be DRY. 如您所见,它们自然是测试的完全相同的结构,要成为DRY,我想将它们提取到shared_example中以使其成为DRY。 The idea is to have many more of these controllers but only actual test and that these controllers just pass in which field to update. 想法是要有更多这样的控制器,但只有实际测试,并且这些控制器只是通过要更新的字段。 It would involve something like 它会涉及到类似
shared_example "update" do
it "updates the object" do
expect do
patch :update, id.object.id, data: { customField: "new value" }
end.to change { object.reload.customField }
end
end
Where customField could be either breed or make in this case and the test would know to update those fields so it is generic and can apply to many of these controllers. 在这种情况下,customField可能是繁殖的,也可能是makeField的,并且测试会知道要更新这些字段,因此它是通用的,可以应用于许多这些控制器。 How can I achieve that or something similar? 我该如何达到目标或类似目标?
shared_example
's block accepts arguments: shared_example
的块接受参数:
shared_example "update" do |custom_field|
it "updates the object (field: #{custom_field})" do
expect do
patch :update, id.object.id, data: { custom_field => "new value" }
end.to change { object.reload.public_send(custom_field) }
end
end
and call it as 并称其为
include_examples 'update', :make
include_examples 'update', :breed
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.