我有以下规格...
describe "successful POST on /user/create" do
it "should redirect to dashboard" do
post '/user/create', {
:name => "dave",
:email => "dave@dave.com",
:password => "another_pass"
}
last_response.should be_redirect
follow_redirect!
last_request.url.should == 'http://example.org/dave/dashboard'
end
end
Sinatra应用程序上的post方法使用rest-client调用外部服务。我需要以某种方式存根其余的客户端调用以发回预设的响应,因此我不必调用实际的HTTP调用。
我的应用程序代码是......
post '/user/create' do
user_name = params[:name]
response = RestClient.post('http://localhost:1885/api/users/', params.to_json, :content_type => :json, :accept => :json)
if response.code == 200
redirect to "/#{user_name}/dashboard"
else
raise response.to_s
end
end
有人可以告诉我如何用RSpec做到这一点吗?我已经用Google搜索并发现了许多博客文章,这些文章从表面上划过,但我实际上找不到答案。我是RSpec时期的新手。
由于
答案 0 :(得分:17)
使用mock作为回复,您可以执行此操作。我对rspec和测试一般都很新,但这对我有用。
describe "successful POST on /user/create" do
it "should redirect to dashboard" do
RestClient = double
response = double
response.stub(:code) { 200 }
RestClient.stub(:post) { response }
post '/user/create', {
:name => "dave",
:email => "dave@dave.com",
:password => "another_pass"
}
last_response.should be_redirect
follow_redirect!
last_request.url.should == 'http://example.org/dave/dashboard'
end
end
答案 1 :(得分:3)
答案 2 :(得分:0)
Instance doubles是必经之路。如果对不存在的方法进行存根,则会出现错误,从而阻止您在生产代码中调用不存在的方法。
response = instance_double(RestClient::Response,
body: {
'isAvailable' => true,
'imageAvailable' => false,
}.to_json)
# or :get, :post, :etc
allow(RestClient::Request).to receive(:execute).and_return(response)