Rails如何模拟Http Post Request

时间:2013-05-31 07:35:06

标签: ruby-on-rails-3.2 mocking rspec2 rspec-rails

在我的控制器中,我已经使用参数发出了这个帖子请求,并且它完美地运行了

parameters = {'email' => "email", 'password' => "password"}      
response = Net::HTTP.post_form(URI.parse('http://example.com/unsubscriptions'), {'q'=>parameters})
      if response.is_a?(Net::HTTPSuccess)
        @msg = "You have successfully unsubscribed."
      else
        @msg = "Resource not found."
      end

在规格控制器中,这是代码

   it "should return success message on a successfull Post request to api" do
              parameters = { "email" => 'email', "password" => "password" }
              Net::HTTP.should_receive(:post_form).with(
                  URI.parse("http://example.com/unsubscriptions"), "q" => parameters
              ).and_return(Net::HTTPSuccess)
              post :unsub_uk, parameters
              #assigns(:msg).should eq("You have successfully unsubscribed.")
              response.should be_success
    end

我无法模拟此Net::HTTP.post_form请求。任何想法或任何其他方式来完成这项任务? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

只需使用gem webmock

Believed解决了这个问题,因为返回应该是Net :: HTTPSuccess。