我有以下传递
的rspec请求规范示例it "increases count by 1" do
attributes = attributes_for(:district)
expect { post admin_districts_path, params: { district: attributes} }.to change { District.count }.by(1)
end
expect
行有点忙,所以我试图将其分解。以下导致错误
it "increases count by 1" do
attributes = attributes_for(:district)
block = { post admin_districts_path, params: { district: attributes} }
expect(block).to change { District.count }.by(1)
end
有错误
syntax error, unexpected '}', expecting keyword_end
为什么会发生这种错误?有没有更简洁的方法来编写这个规范示例?
答案 0 :(得分:4)
我经常在测试中遇到这种长线。我没有创建新的变量来改善阅读,而是将它分成不同的行,如下所示:
it "increases count by 1" do
attributes = attributes_for(:district)
expect do
post admin_districts_path, params: { district: attributes}
end.to change { District.count }.by(1)
end
答案 1 :(得分:2)
此外,您可以创建一个lambda:
block = -> { post admin_districts_path, params: { district: attributes} }
expect(block).to change { District.count }.by(1)
答案 2 :(得分:0)
我更喜欢在相关的describe
块中创建一些辅助方法。这是从样本Rails请求规范中获取的,我假设您已经设置了FactoryBot。像这样:
describe "create /district" do
def create_district_request
@district = build(:district)
params = {district: {name: @district.name etc.}}
post district_path, params: params
end
it "creates a district" do
expect {create_district_request}.to change{District.count}.by(1)
end
end
希望有帮助。