如何在Post#Create中检查Rspec中的现有用户?

时间:2015-10-20 05:13:43

标签: ruby-on-rails ruby ruby-on-rails-4 rspec rspec3

我正在尝试为InvitationsController#Create编写测试。

这是POST http动作。

基本上应该发生的是,一旦post#create首次执行,我们需要做的第一件事就是检查系统中是否存在User以传入的电子邮件通过params[:email]请求上的Post

我很难绕过我的工作方式。

我稍后会重构,但首先我想让测试功能正常工作。

这就是我所拥有的:

describe 'POST #create' do
    context 'when invited user IS an existing user' do
        before :each do
          @users =  [
            attributes_for(:user),
            attributes_for(:user),
            attributes_for(:user)
          ]
        end

        it 'correctly finds User record of invited user' do

          expect {
            post :create, invitation: attributes_for(:member, email: @users.first.email)
          }.to include(@users.first[:email])
        end
    end
end

这是我得到的错误:

1) Users::InvitationsController POST #create when invited user IS an existing user correctly finds User record of invited user
     Failure/Error: expect {
       You must pass an argument rather than a block to use the provided matcher (include "valentin@parisian.org"), or the matcher must implement `supports_block_expectations?`.
     # ./spec/controllers/users/invitations_controller_spec.rb:17:in `block (4 levels) in <top (required)>'

我对这个错误并不感到惊讶,因为测试对我来说感觉不对。如果不在我的controller#action中编写代码,我就无法弄清楚如何测试。

我正在使用FactoryGirl,它可以完美地工作,因为它返回所有数据类型的有效数据。这里的问题是如何让RSpec实际测试我需要的功能。

1 个答案:

答案 0 :(得分:2)

您遇到的错误是语法错误,与您的操作无关。 你在那里的代码被解释为你将一个块({})传递给expect方法。

我将其更改为

it 'correctly finds User record of invited user' do
  post :create, { email: @users.first[:email] }
  expect(response).to include(@users.first[:email])
end

假设创建操作的响应将电子邮件作为纯文本返回,这对我来说似乎很奇怪。

另请注意,我已email直接传递到帖子,因为您提到您在params[:email]中期待它,但您编写的测试似乎是您在params[:invitation][:email]中期待的。 如果是这种情况,请更改该部分。

相关问题