【问题标题】:How to write a rspec for update action for controller?如何为控制器的更新操作编写 rspec?
【发布时间】:2014-01-23 11:32:07
【问题描述】:

我是 Rails 的新手,已经开始着手一个新项目。但我无法为我的更新控制器找到确切的解决方案,这是我的更新控制器。

定义更新 respond_to 做 |格式| 如果@wallet.update(wallet_params) format.html { redirect_to @wallet, notice: '钱包已成功更新。' } format.json { 头 :no_content } 别的 format.html { 渲染动作:'编辑' } format.json { 渲染 json:@wallet.errors,状态::unprocessable_entity } 结尾 结尾 结尾

在我的钱包表中,我有 id、user_id、balance、name。我试过了

描述“PUT #update”做 它“应该更新钱包” 放 :update, id :@wallet.id :wallet{ :name => "xyz", :balance => "20.2"} 结尾 结尾

甚至尝试过一些事情 RSpec test PUT update actionHow to write an RSpec test for a simple PUT update? 但仍然无法解决问题。

【问题讨论】:

标签: rspec ruby-on-rails-4 factory-bot rspec-rails


【解决方案1】:

如果您使用的是 Rails 4,请使用 PATCH 而不是 PUT; PUT 仍然有效,但现在首选 PATCH。要测试它,试试这个:

describe "PATCH #update" do
  context "with good data" do
    it "updates the wallet and redirects" do
      patch :update, id: @wallet.id, wallet: { name: "xyz", balance: "20.2"}
      expect(response).to be_redirect
    end
  end
  context "with bad data" do
    it "does not change the wallet, and re-renders the form" do
      patch :update, id: @wallet.id, wallet: { name: "xyz", balance: "two"}
      expect(response).not_to be_redirect
    end
  end
end

您可以使期望子句更具体,但这只是一个开始。如果你想测试代码的json部分,只需将format: 'json'添加到params hash即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 2023-03-08
    相关资源
    最近更新 更多