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

Rails rspec test failing when trying to add a duplicate node

我正在使用 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

这似乎只是在单元测试中才会发生,通过真实的单词测试它有效。

你的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]) 

会起作用