js请求的rspec控制器规范

时间:2016-04-25 21:43:19

标签: testing rspec controller rspec-rails

在我的控制器规格中,一切正常(更新操作,编辑操作等也通过js请求),但创建操作除外。出于某种原因,它不会更改Task.count,但http响应为200

没有其他回调,在开发环境中它将任务保存在数据库中。这家工厂通过了型号规格。我还试图评论Notification.createTaskCreatorJobConversation.create..,但没有帮助。在我的其他控制器规范中expect { create_action }.to change{Class.count}.by(1)正常工作。

我错过了什么?

电脑板

def create
  @task = Task.new(task_params)
  @task.assigner_id = current_user.id
  if @task.save
    Notification.create(recipient_id: @task.executor_id, sender_id: current_user.id, notifiable: @task, action: "assigned")
    TaskCreatorJob.perform_later(@task, @task.executor, @task.assigner)
    Conversation.create_or_find_conversation(@task.assigner_id, @task.executor_id)
    respond_to do |format|
      format.js
    end     
  else
    respond_to do |format|
      format.js
    end
  end
end

工厂

factory :task do
  content { Faker::Lorem.sentence }
  deadline { Faker::Time.between(DateTime.now + 2, DateTime.now + 3) }
  association :executor, factory: :user
  association :assigner, factory: :user
end

tasks_controller_spec.rb

.....
before(:each) do
    login_user
end

describe "POST create" do

  context "with valid attributes" do
    let!(:user) { create(:user) }
    let!(:profile) { create(:profile, user: @user) }
    let!(:profile_2) { create(:profile, user: user) }
    let!(:conversation) { create(:conversation, sender: @user, recipient: user) }
    subject(:create_action) { xhr :post, :create, user_id: @user.id, task: attributes_for(:task, assigner: @user, executor: user) }

    it "saves the new task in the db" do
      expect{ create_action }.to change{ Task.count }.by(1)
    end

    it "responds with success" do
      create_action
      expect(response).to have_http_status(200)
    end
  end
end

1 个答案:

答案 0 :(得分:0)

似乎在控制器规范中,定义像assigner: @user这样的任务参数是不够的,所以我不得不改变

subject(:create_action) { xhr :post, :create, user_id: @user.id, task: attributes_for(:task, assigner: @user, executor: user) }

subject(:create_action) { xhr :post, :create, user_id: @user.id, task: attributes_for(:task, assigner_id: @user.id, executor_id: user.id) }