简体   繁体   English

Rails / AR –如何在rspec中测试:: update(id,attribute)

[英]Rails / AR – how to test ::update(id, attributes) in rspec

I'm using the active record update method to update multiple records, each with their own individual attributes. 我正在使用活动记录更新方法来更新多个记录,每个记录都有各自的属性。

I facilitate that with this controller code (which works): 我使用以下控制器代码(有效)对此进行了简化:

def update
  keys = params[:schedules].keys
  values = params[:schedules].values
  if Schedule.update(keys, values)
    flash[:notice] = "Schedules were successfully updated."
  else
    flash[:error] = "Unable to update some schedules."
  end
  respond_to do |format|
    format.html { redirect_to responsibilities_path }
  end
end

My question is, how can I test that without hitting the database in rspec ? 我的问题是, 如何在不打rspec中的数据库的情况下进行测试

Here's what I'm trying, but its not working. 这是我正在尝试的方法,但是不起作用。

describe "PATCH update" do

  it "updates the passed in responsibilities" do
    allow(Schedule)
      .to receive(:update)
      .with(["1", "2"], [{"status"=>"2"}, {"status"=>"1"}])
      .and_return(true)
    # results in
    # expected: 1 time with arguments: (["1", "2"], [{"status"=>"2"}, {"status"=>"1"}])
    # received: 0 times
    # Couldn't find Schedule with 'id'=1

    # without the allow, I get
    # Failure/Error: patch :update, schedules: {
    # ActiveRecord::RecordNotFound:
    #   Couldn't find Schedule with 'id'=1
    # # ./app/controllers/responsibilities_controller.rb:18:in `update'
    # # ./lib/authenticated_system.rb:75:in `catch_unauthorized'
    # # ./spec/controllers/responsibilities_controller_spec.rb:59:in `block (5 levels) in <top (required)>'

    patch :update, schedules: {
      "1" => {
        "status" => "2",
      },
      "2" => {
        "status" => "1",
      }
    }
    expect(Schedule)
      .to receive(:update)
      .with(["1", "2"], [{"status"=>"2"}, {"status"=>"1"}])
    expect(flash[:error]).to eq(nil)
    expect(flash[:notice]).not_to eq(nil)
  end
end

I'm on Rails 4.2.4 and rspec 3.0.0 我在Rails 4.2.4和rspec 3.0.0上

your problem is, that you are expecting with 您的问题是,您期望

expect(Schedule)
      .to receive(:update)
      .with(["1", "2"], [{"status"=>"2"}, {"status"=>"1"}])
      .and_call_original     

after calling the patch method. 调用patch方法之后。

That means the request hits your controller before the assertion is established. 这意味着在建立断言之前,请求已命中您的控制器。 To solve that, just put the expect(Schedule) call before the patch call, that also allows you to get rid of the allow(Schedule).to - call. 要解决此问题,只需将Expect(Schedule)调用放在补丁调用之前,这也可以让您摆脱allow(Schedule).to-调用。

Cheers. 干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM