【问题标题】:Cover format.json with rspec用 rspec 覆盖 format.json
【发布时间】:2016-01-02 19:23:54
【问题描述】:

我想知道如何在 rspec 上从我的控制器测试这个 format.json。这是我要介绍的代码:

控制器:

def edit
  @ngo = Ngo.find(params[:id])
  respond_to do |format|
    if request.xhr? 
      if params[:zipcode] 
        format.json { render json: Address.new(Correios::CEP::AddressFinder.get(params[:zipcode]))}
      end
    else
      @phones = Hash[@ngo.phones.map {|phone| [phone.id.to_s ,phone.phone_number]}]
      @phones = @phones.to_json
      format.html 
    end
  end
end

我尝试了一些方法,但没有成功。有谁知道我是怎么做的?谢谢:)

【问题讨论】:

  • 向我们展示一下您尝试过哪些没有奏效的方法会很有帮助。
  • 我试图从 json 得到任何响应,期望(JSON.parse(response.body)).to eq('1231') 但我真的不知道我在做什么待定。
  • 您没有显示您的规范代码...但通常类似的问题在规范文件中错过了render_views。原因:RSpec 试图加速测试,默认不渲染响应。

标签: ruby-on-rails ruby json rspec


【解决方案1】:

这可能对你有用。它涉及我做一些我以前从未尝试过的事情,例如xhr :post, :edit 和模块继承 .get 调用,但我认为它看起来是正确的。让我知道这是否有效!

# spec/controllers/some_controller_spec.rb

describe SomeController, type: :controller do
  context "#edit" do
    it "renders address as json" do
      ngo = double(:ngo, id: "1")
      correios_obj = double(:correios_obj)
      json_address = double(:json_address)
      expect(Ngo).to receive(:find).with("1").and_return(ngo)
      expect(Correios::CEP::AddressFinder).to receive(:get).with("35950").and_return(correios_obj)
      expect(Address).to receive(:new).with(correios_obj).and_return(json_address)
      xhr :post, :edit, zipcode: "35950", id: "1"
      expect(response.body).to eq json_address
    end
  end
end

this SO post 帮助我完成了 xhr 部分

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多