尝试添加重复节点时,Rails rspec测试失败

时间:2015-01-04 03:37:43

标签: ruby-on-rails ruby rspec

我使用rspec来测试我正在开发的API以与我的Android应用程序进行通信。

出于某种原因,我运行此测试

it "tries to add an existing node (same mac address but better signal)" do
  node = Node.create(ssid: "test1", mac: 0, signal: 100)
  post "/api/nodes/", node: { ssid: "test1", mac: 0, signal: 50 }, format: :json
end

我在“mac”字段上收到有关节点重复的错误,但我在控制器中检查这一点以确保它不会发生

def create
  @node = Node.find_by(mac: params[:mac])  #This checks for duplicates but doesnt seem to work
  if @node.nil?
    @node = Node.new(node_params)
    if @node.save                          #somehow its getting to here but the save is failing
      render :show, status: :created       #because there is a duplicate
    end
  else

它似乎只是在单元测试中发生了这种情况,通过真正的单词测试它可以工作。

1 个答案:

答案 0 :(得分:1)

您的params[:mac]nil

post "/api/nodes/", node: { ssid: "test1", mac: 0, signal: 50 }, format: :json

此行发送params[:node][:ssid]params[:node][:mac]params[:node][:signal],因此您应将操作更改为:

def create
  @node = Node.find_by(mac: params[:node][:mac]) 
  if @node.nil?
    @node = Node.new(node_params)
    if @node.save                         
      render :show, status: :created      
    end
  else

PS:我猜你有这个方法:

def node_params
  params.require(:node).permit(:ssid, :mac, signal)
end

如果是:

def node_params
  params.permit(:ssid, :mac, signal)
end

然后在发布时不应该将它们包装在node:中:

post "/api/nodes/", ssid: "test1", mac: 0, signal: 50, format: :json

@node = Node.find_by(mac: params[:mac]) 

将起作用