英文:
Can I pass a block to it_behaves_like in Rails RSpec?
问题
在使用it_behaves_like
时,你想要扩展预期列表是否可以传递一个块?例如,你这样写:
it_behaves_like "success" do
expect(response['id']).to eq(1)
end
希望RSpec将其编译成这样:
it "returns data" do
post "/api/users", params: params
expect(response.status).to eq(201)
expect(response['id']).to eq(1)
end
上述代码显然不按预期工作,但我想知道如何编写它,以便RSpec能够理解并按照我上面期望的结果进行编译。这种情况是否可行?
不幸的是,RSpec不会按你期望的方式处理它。it_behaves_like
并不支持在块内添加额外的期望。你需要在shared_examples
中定义完整的示例,而不能在调用it_behaves_like
时添加额外的期望。
要实现你的期望结果,你可以将额外的期望添加到shared_examples
中,如下所示:
shared_examples 'success' do
let(:params) { key: 'value' }
it 'returns data' do
post '/api/users', params: params
expect(response.status).to eq(201)
expect(response['id']).to eq(1)
end
end
然后,你可以使用it_behaves_like
调用它:
it_behaves_like 'success'
这将在测试中包括所有你想要的期望。
英文:
Providing that I have a shared example:
shared_examples 'success' do
let(:params) { key: "value" }
it "returns data" do
post "/api/users", params: params
expect(response.status).to eq (201)
end
end
When I use this shared example with it_behaves_like
, can I pass a block to it to extends the list of expected?
For example, I write it like this:
it_behaves_like "success" do
expect(response['id]).to eq(1)
end
in hope of rspec to compile it like this:
it "returns data" do
post "/api/users", params: params
expect(response.status).to eq (201)
expect(response['id]).to eq(1)
end
The above code is obviously not working as I wanted, but I want to know how to write it so that RSpec can understand it like my expected outcome above. Is it possible?
答案1
得分: 1
你可以将其分成一个共享上下文,用于执行API请求,和一个共享示例,用于检查状态代码,例如:
shared_context 'request' do
before do
post '/api/users', params: params
end
end
shared_examples 'success' do
it 'returns with 201 status code' do
expect(response.status).to eq(201)
end
end
然后可以组合它们:
describe 'a successful request' do
include_context 'request' do
let(:params) { { key: 'value' } }
end
it_behaves_like 'success'
it 'returns data' do
expect(response['id']).to eq(1)
end
end
英文:
You could separate it into a shared context which performs the API request and a shared example which checks the status code, e.g.:
shared_context 'request' do
before do
post '/api/users', params: params
end
end
shared_examples 'success' do
it 'returns with 201 status code' do
expect(response.status).to eq (201)
end
end
These can then be combined:
describe 'a successful request' do
include_context 'request' do
let(:params) { { key: 'value' } }
end
it_behaves_like 'success'
it 'returns data' do
expect(response['id']).to eq(1)
end
end
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论