Rspec Controller Post使用Twilio Ruby创建

时间:2014-12-29 20:43:38

标签: ruby-on-rails rspec twilio

我是Rspec测试的新手,很抱歉,如果我的代码中的问题显然是错误的。我正在尝试测试是否在向我的Twilio号码发送短信时它是否保存。

这是我的controllers / messages_controller.rb

require 'twilio-ruby'

class MessagesController < AppController
  include Webhookable

  skip_before_action :verify_authenticity_token
  skip_before_action :authenticate_user!

  def create
    Message.create!(parent_id: nil,
               content_type: "sms",
               content: params['Body'],
               origin: params['From'].gsub("+1", ""),
               destination: params['To'].gsub("+1", ""),
               received_at: Time.now())
respond_to do |format|
  format.all { render :nothing => true, :status => 200 }
end
end

end

这是我的spec / controllers / messages_controller_spec.rb,其中我使用let!()来创建create方法在其回调中使用的一堆对象

require 'rails_helper'

RSpec.describe MessagesController, :type => :controller do
describe "#create" do
    let(:message) { build(:message) }
    let!(:hotel)  { create(:hotel) }
    let!(:group)  { create(:group) }
    let!(:guest)  { create(:test_guest) }
    let!(:user)   { create(:user) }
    let!(:visit)  { create(:visit) }
    let!(:group_user) { create(:group_user) }

    context "when new text message comes in" do
        it "saves the message" do
            post :create, :Body => message.content, :From => message.origin, :To => message.destination
            expect(Message.last).to be_truthy
        end
    end
end
end

这是运行测试时失败的消息

Failures:

1) MessagesController#create when new text message comes in saves the message
 Failure/Error: let!(:visit)  { create(:visit) }
 NoMethodError:
   undefined method `users' for nil:NilClass
 # ./app/models/hotel.rb:30:in `managers'
 # ./app/models/concerns/visit_message.rb:9:in `create_check_in_messages'
 # ./spec/controllers/messages_controller_spec.rb:10:in `block (3 levels) in <top (required)>'

从那里我去了一个格子模型/ hotel.rb:30

def managers
groups.first.users.managers.order("created_at ASC")
end

然而,我认为自从我使用let!(:group){create(:group)}后,当我运行测试时这不会是nil。任何方向或建设性的批评都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

我能看到的一件事是你创建对象的顺序不正确

let(:message) { build(:message) }
let!(:hotel)  { create(:hotel) }
let!(:group)  { create(:group) }
let!(:user)   { create(:user) }
let!(:group_user) { create(:group_user, :group => group, :user => user) }
let!(:guest)  { create(:test_guest) }
let!(:visit)  { create(:visit) }

在创建访问之前,您应该使用适当的群组和用户创建群组userjoin记录group_user